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

Annotation of /Sprout/CustomAttributes.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.41 - (view) (download) (as text)

1 : parrello 1.1 #!/usr/bin/perl -w
2 :    
3 :     package CustomAttributes;
4 :    
5 :     use strict;
6 :     use Tracer;
7 : parrello 1.13 use Stats;
8 : parrello 1.28 use Time::HiRes qw(time);
9 : parrello 1.33 use FIGRules;
10 : parrello 1.40 use base qw(ERDB);
11 : parrello 1.1
12 :     =head1 Custom SEED Attribute Manager
13 :    
14 :     =head2 Introduction
15 :    
16 :     The Custom SEED Attributes Manager allows the user to upload and retrieve
17 :     custom data for SEED objects. It uses the B<ERDB> database system to
18 : parrello 1.10 store the attributes.
19 :    
20 :     Attributes are organized by I<attribute key>. Attribute values are
21 :     assigned to I<objects>. In the real world, objects have types and IDs;
22 :     however, to the attribute database only the ID matters. This will create
23 :     a problem if we have a single ID that applies to two objects of different
24 :     types, but it is more consistent with the original attribute implementation
25 : parrello 1.11 in the SEED (which this implementation replaces).
26 : parrello 1.10
27 : parrello 1.11 The actual attribute values are stored as a relationship between the attribute
28 :     keys and the objects. There can be multiple values for a single key/object pair.
29 : parrello 1.1
30 : parrello 1.19 =head3 Object IDs
31 :    
32 :     The object ID is normally represented as
33 :    
34 :     I<type>:I<id>
35 :    
36 :     where I<type> is the object type (C<Role>, C<Coupling>, etc.) and I<id> is
37 :     the actual object ID. Note that the object type must consist of only upper- and
38 :     lower-case letters! Thus, C<GenomeGroup> is a valid object type, but
39 :     C<genome_group> is not. Given that restriction, the object ID
40 :    
41 :     Family:aclame|cluster10
42 :    
43 :     would represent the FIG family C<aclame|cluster10>. For historical reasons,
44 :     there are three exceptions: subsystems, genomes, and features do not need
45 :     a type. So, for PEG 3361 of Streptomyces coelicolor A3(2), you simply code
46 :    
47 :     fig|100226.1.peg.3361
48 :    
49 :     The methods L</ParseID> and L</FormID> can be used to make this all seem
50 :     more consistent. Given any object ID string, L</ParseID> will convert it to an
51 :     object type and ID, and given any object type and ID, L</FormID> will
52 :     convert it to an object ID string. The attribute database is pretty
53 :     freewheeling about what it will allow for an ID; however, for best
54 :     results, the type should match an entity type from a Sprout genetics
55 :     database. If this rule is followed, then the database object
56 :     corresponding to an ID in the attribute database could be retrieved using
57 :     L</GetTargetObject> method.
58 :    
59 :     my $object = CustomAttributes::GetTargetObject($sprout, $idValue);
60 :    
61 :     =head3 Retrieval and Logging
62 :    
63 : parrello 1.1 The full suite of ERDB retrieval capabilities is provided. In addition,
64 :     custom methods are provided specific to this application. To get all
65 : parrello 1.6 the values of the attribute C<essential> in a specified B<Feature>, you
66 : parrello 1.1 would code
67 :    
68 : parrello 1.10 my @values = $attrDB->GetAttributes($fid, 'essential');
69 : parrello 1.1
70 : parrello 1.10 where I<$fid> contains the ID of the desired feature.
71 : parrello 1.1
72 : parrello 1.20 Keys can be split into two pieces using the splitter value defined in the
73 :     constructor (the default is C<::>). The first piece of the key is called
74 :     the I<real key>. This portion of the key must be defined using the
75 :     web interface (C<Attributes.cgi>). The second portion of the key is called
76 :     the I<sub key>, and can take any value.
77 : parrello 1.1
78 : parrello 1.18 Major attribute activity is recorded in a log (C<attributes.log>) in the
79 :     C<$FIG_Config::var> directory. The log reports the user name, time, and
80 :     the details of the operation. The user name will almost always be unknown,
81 : parrello 1.20 the exception being when it is specified in this object's constructor
82 :     (see L</new>).
83 : parrello 1.18
84 : parrello 1.1 =head2 FIG_Config Parameters
85 :    
86 :     The following configuration parameters are used to manage custom attributes.
87 :    
88 :     =over 4
89 :    
90 :     =item attrDbms
91 :    
92 :     Type of database manager used: C<mysql> for MySQL or C<pg> for PostGres.
93 :    
94 :     =item attrDbName
95 :    
96 :     Name of the attribute database.
97 :    
98 :     =item attrHost
99 :    
100 :     Name of the host server for the database. If omitted, the current host
101 :     is used.
102 :    
103 :     =item attrUser
104 :    
105 :     User name for logging in to the database.
106 :    
107 :     =item attrPass
108 :    
109 :     Password for logging in to the database.
110 :    
111 :     =item attrPort
112 :    
113 :     TCP/IP port for accessing the database.
114 :    
115 :     =item attrSock
116 :    
117 :     Socket name used to access the database. If omitted, the default socket
118 :     will be used.
119 :    
120 :     =item attrDBD
121 :    
122 :     Fully-qualified file name for the database definition XML file. This file
123 :     functions as data to the attribute management process, so if the data is
124 :     moved, this file must go with it.
125 :    
126 : parrello 1.33 =item attr_default_table
127 :    
128 :     Name of the default relationship for attribute values. If not present,
129 :     C<HasValueFor> is used.
130 :    
131 : parrello 1.1 =back
132 :    
133 :     =head2 Public Methods
134 :    
135 :     =head3 new
136 :    
137 : parrello 1.31 my $attrDB = CustomAttributes->new(%options);
138 : parrello 1.1
139 : parrello 1.18 Construct a new CustomAttributes object. The following options are
140 :     supported.
141 : parrello 1.3
142 :     =over 4
143 :    
144 :     =item splitter
145 :    
146 :     Value to be used to split attribute values into sections in the
147 : parrello 1.18 L</Fig Replacement Methods>. The default is a double colon C<::>,
148 :     and should only be overridden in extreme circumstances.
149 :    
150 :     =item user
151 :    
152 :     Name of the current user. This will appear in the attribute log.
153 : parrello 1.3
154 : parrello 1.40 =item dbd
155 :    
156 :     Filename for the DBD. If unspecified, the default DBD is used.
157 :    
158 : parrello 1.3 =back
159 : parrello 1.1
160 :     =cut
161 :    
162 :     sub new {
163 :     # Get the parameters.
164 : parrello 1.18 my ($class, %options) = @_;
165 : parrello 1.33 # Get the name ofthe default table.
166 : parrello 1.1 # Connect to the database.
167 :     my $dbh = DBKernel->new($FIG_Config::attrDbms, $FIG_Config::attrDbName,
168 :     $FIG_Config::attrUser, $FIG_Config::attrPass,
169 :     $FIG_Config::attrPort, $FIG_Config::attrHost,
170 :     $FIG_Config::attrSock);
171 :     # Create the ERDB object.
172 : parrello 1.40 my $xmlFileName = ($options{dbd} ? $options{dbd} : $FIG_Config::attrDBD);
173 : parrello 1.41 my $retVal = ERDB::new($class, $dbh, $xmlFileName, %options);
174 : parrello 1.3 # Store the splitter value.
175 : parrello 1.18 $retVal->{splitter} = $options{splitter} || '::';
176 :     # Store the user name.
177 :     $retVal->{user} = $options{user} || '<unknown>';
178 :     Trace("User $retVal->{user} selected for attribute object.") if T(3);
179 : parrello 1.33 # Compute the default value table name. If it's not overridden, the
180 :     # default is HasValueFor.
181 :     $retVal->{defaultRel} = $FIG_Config::attr_default_table || 'HasValueFor';
182 : parrello 1.1 # Return the result.
183 :     return $retVal;
184 :     }
185 :    
186 : parrello 1.10 =head3 StoreAttributeKey
187 :    
188 : parrello 1.33 $attrDB->StoreAttributeKey($attributeName, $notes, \@groups, $table);
189 : parrello 1.10
190 :     Create or update an attribute for the database.
191 :    
192 :     =over 4
193 : parrello 1.1
194 :     =item attributeName
195 :    
196 : parrello 1.20 Name of the attribute (the real key). If it does not exist already, it will be created.
197 : parrello 1.1
198 :     =item notes
199 :    
200 :     Descriptive notes about the attribute. It is presumed to be raw text, not HTML.
201 :    
202 : parrello 1.10 =item groups
203 : parrello 1.1
204 : parrello 1.10 Reference to a list of the groups to which the attribute should be associated.
205 :     This will replace any groups to which the attribute is currently attached.
206 : parrello 1.1
207 : parrello 1.33 =item table
208 :    
209 :     The name of the relationship in which the attribute's values are to be stored.
210 :     If empty or undefined, the default relationship (usually C<HasValueFor>) will be
211 :     assumed.
212 :    
213 : parrello 1.1 =back
214 :    
215 :     =cut
216 :    
217 : parrello 1.3 sub StoreAttributeKey {
218 : parrello 1.1 # Get the parameters.
219 : parrello 1.33 my ($self, $attributeName, $notes, $groups, $table) = @_;
220 : parrello 1.8 # Declare the return variable.
221 :     my $retVal;
222 : parrello 1.33 # Default the table name.
223 :     if (! $table) {
224 :     $table = $self->{defaultRel};
225 :     }
226 : parrello 1.1 # Validate the initial input values.
227 : parrello 1.20 if ($attributeName =~ /$self->{splitter}/) {
228 : parrello 1.1 Confess("Invalid attribute name \"$attributeName\" specified.");
229 : parrello 1.33 } elsif (! $notes) {
230 :     Confess("Missing description for $attributeName.");
231 :     } elsif (! grep { $_ eq $table } $self->GetConnectingRelationships('AttributeKey')) {
232 :     Confess("Invalid relationship name \"$table\" specified as a custom attribute table.");
233 : parrello 1.1 } else {
234 : parrello 1.18 # Create a variable to hold the action to be displayed for the log (Add or Update).
235 :     my $action;
236 : parrello 1.10 # Okay, we're ready to begin. See if this key exists.
237 :     my $attribute = $self->GetEntity('AttributeKey', $attributeName);
238 :     if (defined($attribute)) {
239 :     # It does, so we do an update.
240 : parrello 1.18 $action = "Update Key";
241 : parrello 1.10 $self->UpdateEntity('AttributeKey', $attributeName,
242 : parrello 1.33 { description => $notes,
243 :     'relationship-name' => $table});
244 : parrello 1.10 # Detach the key from its current groups.
245 :     $self->Disconnect('IsInGroup', 'AttributeKey', $attributeName);
246 :     } else {
247 :     # It doesn't, so we do an insert.
248 : parrello 1.18 $action = "Insert Key";
249 : parrello 1.10 $self->InsertObject('AttributeKey', { id => $attributeName,
250 : parrello 1.33 description => $notes,
251 :     'relationship-name' => $table});
252 : parrello 1.8 }
253 : parrello 1.10 # Attach the key to the specified groups. (We presume the groups already
254 :     # exist.)
255 :     for my $group (@{$groups}) {
256 :     $self->InsertObject('IsInGroup', { 'from-link' => $attributeName,
257 :     'to-link' => $group });
258 : parrello 1.1 }
259 : parrello 1.18 # Log the operation.
260 :     $self->LogOperation($action, $attributeName, "Group list is " . join(" ", @{$groups}));
261 : parrello 1.1 }
262 :     }
263 :    
264 :    
265 : parrello 1.3 =head3 DeleteAttributeKey
266 :    
267 : parrello 1.31 my $stats = $attrDB->DeleteAttributeKey($attributeName);
268 : parrello 1.1
269 :     Delete an attribute from the custom attributes database.
270 :    
271 :     =over 4
272 :    
273 : parrello 1.10 =item attributeName
274 : parrello 1.1
275 : parrello 1.10 Name of the attribute to delete.
276 : parrello 1.1
277 : parrello 1.10 =item RETURN
278 : parrello 1.1
279 : parrello 1.10 Returns a statistics object describing the effects of the deletion.
280 : parrello 1.1
281 :     =back
282 :    
283 :     =cut
284 :    
285 : parrello 1.3 sub DeleteAttributeKey {
286 : parrello 1.1 # Get the parameters.
287 : parrello 1.10 my ($self, $attributeName) = @_;
288 :     # Delete the attribute key.
289 :     my $retVal = $self->Delete('AttributeKey', $attributeName);
290 : parrello 1.18 # Log this operation.
291 :     $self->LogOperation("Delete Key", $attributeName, "Key will no longer be available for use by anyone.");
292 : parrello 1.10 # Return the result.
293 :     return $retVal;
294 : parrello 1.31
295 : parrello 1.10 }
296 :    
297 :     =head3 NewName
298 :    
299 : parrello 1.31 my $text = CustomAttributes::NewName();
300 : parrello 1.10
301 :     Return the string used to indicate the user wants to add a new attribute.
302 :    
303 :     =cut
304 :    
305 :     sub NewName {
306 :     return "(new)";
307 : parrello 1.1 }
308 :    
309 : parrello 1.11 =head3 LoadAttributesFrom
310 :    
311 : parrello 1.32 C<< my $stats = $attrDB->LoadAttributesFrom($fileName, %options); >>
312 :    
313 : parrello 1.11 Load attributes from the specified tab-delimited file. Each line of the file must
314 :     contain an object ID in the first column, an attribute key name in the second
315 : parrello 1.33 column, and attribute values in the remaining columns. The attribute values must
316 : parrello 1.20 be assembled into a single value using the splitter code. In addition, the key names may
317 :     contain a splitter. If this is the case, the portion of the key after the splitter is
318 :     treated as a subkey.
319 : parrello 1.11
320 :     =over 4
321 :    
322 :     =item fileName
323 :    
324 : parrello 1.20 Name of the file from which to load the attributes, or an open handle for the file.
325 :     (This last enables the method to be used in conjunction with the CGI form upload
326 :     control.)
327 : parrello 1.11
328 :     =item options
329 :    
330 :     Hash of options for modifying the load process.
331 :    
332 :     =item RETURN
333 :    
334 :     Returns a statistics object describing the load.
335 :    
336 :     =back
337 :    
338 :     Permissible option values are as follows.
339 :    
340 :     =over 4
341 :    
342 : parrello 1.33 =item mode
343 :    
344 :     Loading mode. Legal values are C<low_priority> (which reduces the task priority
345 :     of the load) and C<concurrent> (which reduces the locking cost of the load). The
346 :     default is a normal load.
347 :    
348 : parrello 1.11 =item append
349 :    
350 :     If TRUE, then the attributes will be appended to existing data; otherwise, the
351 :     first time a key name is encountered, it will be erased.
352 :    
353 : parrello 1.20 =item archive
354 :    
355 : parrello 1.32 If specified, the name of a file into which the incoming data should be saved.
356 :     If I<resume> is also specified, only the lines actually loaded will be put
357 :     into this file.
358 : parrello 1.20
359 :     =item objectType
360 :    
361 :     If specified, the specified object type will be prefixed to each object ID.
362 :    
363 : parrello 1.28 =item resume
364 :    
365 :     If specified, key-value pairs already in the database will not be reinserted.
366 : parrello 1.32 Specify a number to start checking after the specified number of lines and
367 :     then admit everything after the first line not yet loaded. Specify C<careful>
368 :     to check every single line. Specify C<none> to ignore this option. The default
369 :     is C<none>. So, if you believe that a previous load failed somewhere after 50000
370 :     lines, a resume value of C<50000> would skip 50000 lines in the file, then
371 :     check each line after that until it finds one not already in the database. The
372 :     first such line found and all lines after that will be loaded. On the other
373 :     hand, if you have a file of 100000 records, and some have been loaded and some
374 :     not, you would use the word C<careful>, so that every line would be checked before
375 :     it is inserted. A resume of C<0> will start checking the first line of the
376 :     input file and then begin loading once it finds a line not in the database.
377 :    
378 :     =item chunkSize
379 :    
380 :     Number of lines to load in each burst. The default is 10,000.
381 : parrello 1.28
382 : parrello 1.11 =back
383 :    
384 :     =cut
385 :    
386 :     sub LoadAttributesFrom {
387 :     # Get the parameters.
388 :     my ($self, $fileName, %options) = @_;
389 :     # Declare the return variable.
390 : parrello 1.32 my $retVal = Stats->new('keys', 'values', 'linesOut');
391 : parrello 1.27 # Initialize the timers.
392 : parrello 1.33 my ($eraseTime, $archiveTime, $checkTime) = (0, 0, 0);
393 : parrello 1.11 # Check for append mode.
394 :     my $append = ($options{append} ? 1 : 0);
395 : parrello 1.28 # Check for resume mode.
396 : parrello 1.32 my $resume = (defined($options{resume}) ? $options{resume} : 'none');
397 : parrello 1.11 # Create a hash of key names found.
398 :     my %keyHash = ();
399 : parrello 1.33 # Create a hash of table names to files. Most attributes go into the HasValueFor
400 :     # table, but some are put into other tables. Each table name will be mapped
401 :     # to a sub-hash with keys "fileName" (output file for the table) and "count"
402 :     # (number of lines in the file).
403 :     my %tableHash = ();
404 : parrello 1.32 # Compute the chunk size.
405 :     my $chunkSize = ($options{chunkSize} ? $options{chunkSize} : 10000);
406 : parrello 1.20 # Open the file for input. Note we must anticipate the possibility of an
407 : parrello 1.33 # open filehandle being passed in. This occurs when the user is submitting
408 :     # the load file over the web.
409 : parrello 1.20 my $fh;
410 : parrello 1.21 if (ref $fileName) {
411 : parrello 1.20 Trace("Using file opened by caller.") if T(3);
412 :     $fh = $fileName;
413 :     } else {
414 :     Trace("Attributes will be loaded from $fileName.") if T(3);
415 :     $fh = Open(undef, "<$fileName");
416 :     }
417 : parrello 1.32 # Trace the mode.
418 : parrello 1.33 if (T(3)) {
419 :     if ($options{mode}) {
420 :     Trace("Mode is $options{mode}.")
421 :     } else {
422 :     Trace("No mode specified.")
423 :     }
424 :     }
425 : parrello 1.20 # Now check to see if we need to archive.
426 :     my $ah;
427 : parrello 1.32 if (exists $options{archive}) {
428 :     my $ah = Open(undef, ">$options{archive}");
429 : parrello 1.20 Trace("Load file will be archived to $options{archive}.") if T(3);
430 :     }
431 : parrello 1.28 # Insure we recover from errors.
432 : parrello 1.20 eval {
433 : parrello 1.32 # If we have a resume number, process it here.
434 :     if ($resume =~ /\d+/) {
435 :     Trace("Skipping $resume lines.") if T(2);
436 :     my $startTime = time();
437 :     # Skip the specified number of lines.
438 :     for (my $skipped = 0; ! eof($fh) && $skipped < $resume; $skipped++) {
439 :     my $line = <$fh>;
440 :     $retVal->Add(skipped => 1);
441 :     }
442 :     $checkTime += time() - $startTime;
443 :     }
444 : parrello 1.20 # Loop through the file.
445 : parrello 1.32 Trace("Starting load.") if T(2);
446 : parrello 1.20 while (! eof $fh) {
447 :     # Read the current line.
448 :     my ($id, $key, @values) = Tracer::GetLine($fh);
449 :     $retVal->Add(linesIn => 1);
450 :     # Do some validation.
451 :     if (! $id) {
452 :     # We ignore blank lines.
453 :     $retVal->Add(blankLines => 1);
454 :     } elsif (substr($id, 0, 1) eq '#') {
455 :     # A line beginning with a pound sign is a comment.
456 :     $retVal->Add(comments => 1);
457 :     } elsif (! defined($key)) {
458 :     # An ID without a key is a serious error.
459 :     my $lines = $retVal->Ask('linesIn');
460 :     Confess("Line $lines in $fileName has no attribute key.");
461 : parrello 1.23 } elsif (! @values) {
462 :     # A line with no values is not allowed.
463 :     my $lines = $retVal->Ask('linesIn');
464 :     Trace("Line $lines for key $key has no attribute values.") if T(1);
465 :     $retVal->Add(skipped => 1);
466 : parrello 1.20 } else {
467 : parrello 1.32 # Check to see if we need to fix up the object ID.
468 :     if ($options{objectType}) {
469 :     $id = "$options{objectType}:$id";
470 :     }
471 : parrello 1.20 # The key contains a real part and an optional sub-part. We need the real part.
472 :     my ($realKey, $subKey) = $self->SplitKey($key);
473 :     # Now we need to check for a new key.
474 :     if (! exists $keyHash{$realKey}) {
475 : parrello 1.32 my $keyObject = $self->GetEntity(AttributeKey => $realKey);
476 :     if (! defined($keyObject)) {
477 :     # Here the specified key does not exist, which is an error.
478 : parrello 1.20 my $line = $retVal->Ask('linesIn');
479 :     Confess("Attribute \"$realKey\" on line $line of $fileName not found in database.");
480 :     } else {
481 : parrello 1.33 # Make sure we know this is no longer a new key. We do this by putting
482 :     # its table name in the key hash.
483 :     $keyHash{$realKey} = $keyObject->PrimaryValue('AttributeKey(relationship-name)');
484 : parrello 1.20 $retVal->Add(keys => 1);
485 : parrello 1.32 # If this is NOT append mode, erase the key. This does not delete the key
486 :     # itself; it just clears out all the values.
487 : parrello 1.20 if (! $append) {
488 : parrello 1.27 my $startTime = time();
489 : parrello 1.20 $self->EraseAttribute($realKey);
490 : parrello 1.27 $eraseTime += time() - $startTime;
491 :     Trace("Attribute $realKey erased.") if T(3);
492 : parrello 1.20 }
493 : parrello 1.11 }
494 : parrello 1.20 Trace("Key $realKey found.") if T(3);
495 : parrello 1.11 }
496 : parrello 1.28 # If we're in resume mode, check to see if this insert is redundant.
497 :     my $ok = 1;
498 : parrello 1.32 if ($resume ne 'none') {
499 : parrello 1.28 my $startTime = time();
500 :     my $count = $self->GetAttributes($id, $key, @values);
501 : parrello 1.32 if ($count) {
502 :     # Here the record is found, so we skip it.
503 :     $ok = 0;
504 :     $retVal->Add(skipped => 1);
505 :     } else {
506 :     # Here the record is not found. If we're in non-careful mode, we
507 :     # stop resume checking at this point.
508 :     if ($resume ne 'careful') {
509 :     $resume = 'none';
510 :     }
511 :     }
512 : parrello 1.28 $checkTime += time() - $startTime;
513 :     }
514 :     if ($ok) {
515 : parrello 1.32 # We're in business. First, archive this row.
516 :     if (defined $ah) {
517 :     my $startTime = time();
518 :     Tracer::PutLine($ah, [$id, $key, @values]);
519 :     $archiveTime += time() - $startTime;
520 :     }
521 :     # We need to format the attribute data so it will work
522 :     # as if it were a load file. This means we join the
523 :     # values.
524 :     my $valueString = join('::', @values);
525 : parrello 1.33 # Now we need to get access to the key's load file. Check for it in the
526 :     # table hash.
527 :     my $keyTable = $keyHash{$realKey};
528 :     if (! exists $tableHash{$keyTable}) {
529 :     # This is a new table, so we need to set it up. First, we get
530 :     # a temporary file for it.
531 :     my $tempFileName = FIGRules::GetTempFileName(sessionID => $$ . $keyTable,
532 :     extension => 'dtx');
533 :     my $oh = Open(undef, ">$tempFileName");
534 :     # Now we create its descriptor in the table hash.
535 :     $tableHash{$keyTable} = {fileName => $tempFileName, handle => $oh, count => 0};
536 :     }
537 :     # Everything is all set up, so we put the value in the temporary file and
538 : parrello 1.32 # count it.
539 : parrello 1.33 my $tableData = $tableHash{$keyTable};
540 : parrello 1.28 my $startTime = time();
541 : parrello 1.33 Tracer::PutLine($tableData->{handle}, [$realKey, $id, $subKey, $valueString]);
542 : parrello 1.32 $archiveTime += time() - $startTime;
543 :     $retVal->Add(linesOut => 1);
544 : parrello 1.33 $tableData->{count}++;
545 :     # See if it's time to load a chunk.
546 :     if ($tableData->{count} >= $chunkSize) {
547 :     # We've filled a chunk, so it's time.
548 :     close $tableData->{handle};
549 :     $self->_LoadAttributeTable($keyTable, $tableData->{fileName}, $retVal);
550 :     # Reset for the next chunk.
551 :     $tableData->{count} = 0;
552 :     $tableData->{handle} = Open(undef, ">$tableData->{fileName}");
553 : parrello 1.32 }
554 : parrello 1.28 } else {
555 :     # Here we skipped because of resume mode.
556 :     $retVal->Add(resumeSkip => 1);
557 :     }
558 : parrello 1.33 Trace($retVal->Ask('values') . " values processed.") if $retVal->Check(values => 1000) && T(3);
559 : parrello 1.11 }
560 : parrello 1.20 }
561 : parrello 1.32 # Now we close the archive file. Note we undefine the handle so the error methods know
562 :     # not to worry.
563 :     if (defined $ah) {
564 :     close $ah;
565 :     undef $ah;
566 :     }
567 : parrello 1.33 # Now we load the residual from the temporary files (if any). This time we'll do an
568 : parrello 1.32 # analyze as well.
569 : parrello 1.33 for my $tableName (keys %tableHash) {
570 :     # Get the data for this table.
571 :     my $tableData = $tableHash{$tableName};
572 :     # Close the handle. ERDB will re-open it for input later.
573 :     close $tableData->{handle};
574 :     # Check to see if there's anything left to load.
575 :     if ($tableData->{count} > 0) {
576 :     # Yes, load the data.
577 :     $self->_LoadAttributeTable($tableName, $tableData->{fileName}, $retVal);
578 :     }
579 :     # Regardless of whether additional loading was required, we need to
580 :     # analyze the table for performance.
581 :     my $startTime = time();
582 :     $self->Analyze($tableName);
583 :     $retVal->Add(analyzeTime => time() - $startTime);
584 :     }
585 : parrello 1.32 Trace("Attribute load successful.") if T(2);
586 : parrello 1.20 };
587 :     # Check for an error.
588 :     if ($@) {
589 : parrello 1.28 # Here we have an error. Display the error message.
590 : parrello 1.20 my $message = $@;
591 : parrello 1.28 Trace("Error during attribute load: $message") if T(0);
592 :     $retVal->AddMessage($message);
593 : parrello 1.32 # Close the archive file if it's open. The archive file can sometimes provide
594 :     # clues as to what happened.
595 :     if (defined $ah) {
596 :     close $ah;
597 :     }
598 : parrello 1.28 }
599 : parrello 1.32 # Store the timers.
600 :     $retVal->Add(eraseTime => $eraseTime);
601 :     $retVal->Add(archiveTime => $archiveTime);
602 :     $retVal->Add(checkTime => $checkTime);
603 : parrello 1.11 # Return the result.
604 :     return $retVal;
605 :     }
606 :    
607 : parrello 1.13 =head3 BackupKeys
608 :    
609 : parrello 1.31 my $stats = $attrDB->BackupKeys($fileName, %options);
610 : parrello 1.13
611 :     Backup the attribute key information from the attribute database.
612 :    
613 :     =over 4
614 :    
615 :     =item fileName
616 :    
617 :     Name of the output file.
618 :    
619 :     =item options
620 :    
621 :     Options for modifying the backup process.
622 :    
623 :     =item RETURN
624 :    
625 :     Returns a statistics object for the backup.
626 :    
627 :     =back
628 :    
629 :     Currently there are no options. The backup is straight to a text file in
630 :     tab-delimited format. Each key is backup up to two lines. The first line
631 :     is all of the data from the B<AttributeKey> table. The second is a
632 :     tab-delimited list of all the groups.
633 :    
634 :     =cut
635 :    
636 :     sub BackupKeys {
637 :     # Get the parameters.
638 :     my ($self, $fileName, %options) = @_;
639 :     # Declare the return variable.
640 :     my $retVal = Stats->new();
641 :     # Open the output file.
642 :     my $fh = Open(undef, ">$fileName");
643 :     # Set up to read the keys.
644 :     my $keyQuery = $self->Get(['AttributeKey'], "", []);
645 :     # Loop through the keys.
646 :     while (my $keyData = $keyQuery->Fetch()) {
647 :     $retVal->Add(key => 1);
648 :     # Get the fields.
649 : parrello 1.33 my ($id, $type, $tableName, $description) =
650 :     $keyData->Values(['AttributeKey(id)', 'AttributeKey(relationship-name)',
651 :     'AttributeKey(description)']);
652 : parrello 1.13 # Escape any tabs or new-lines in the description.
653 :     my $escapedDescription = Tracer::Escape($description);
654 :     # Write the key data to the output.
655 : parrello 1.33 Tracer::PutLine($fh, [$id, $type, $tableName, $escapedDescription]);
656 : parrello 1.13 # Get the key's groups.
657 :     my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(from-link) = ?", [$id],
658 :     'IsInGroup(to-link)');
659 :     $retVal->Add(memberships => scalar(@groups));
660 :     # Write them to the output. Note we put a marker at the beginning to insure the line
661 :     # is nonempty.
662 :     Tracer::PutLine($fh, ['#GROUPS', @groups]);
663 :     }
664 : parrello 1.18 # Log the operation.
665 :     $self->LogOperation("Backup Keys", $fileName, $retVal->Display());
666 : parrello 1.13 # Return the result.
667 :     return $retVal;
668 :     }
669 :    
670 :     =head3 RestoreKeys
671 :    
672 : parrello 1.31 my $stats = $attrDB->RestoreKeys($fileName, %options);
673 : parrello 1.13
674 :     Restore the attribute keys and groups from a backup file.
675 :    
676 :     =over 4
677 :    
678 :     =item fileName
679 :    
680 :     Name of the file containing the backed-up keys. Each key has a pair of lines,
681 :     one containing the key data and one listing its groups.
682 :    
683 :     =back
684 :    
685 :     =cut
686 :    
687 :     sub RestoreKeys {
688 :     # Get the parameters.
689 :     my ($self, $fileName, %options) = @_;
690 :     # Declare the return variable.
691 :     my $retVal = Stats->new();
692 :     # Set up a hash to hold the group IDs.
693 :     my %groups = ();
694 :     # Open the file.
695 :     my $fh = Open(undef, "<$fileName");
696 :     # Loop until we're done.
697 :     while (! eof $fh) {
698 :     # Get a key record.
699 : parrello 1.33 my ($id, $tableName, $description) = Tracer::GetLine($fh);
700 : parrello 1.13 if ($id eq '#GROUPS') {
701 :     Confess("Group record found when key record expected.");
702 :     } elsif (! defined($description)) {
703 :     Confess("Invalid format found for key record.");
704 :     } else {
705 :     $retVal->Add("keyIn" => 1);
706 :     # Add this key to the database.
707 : parrello 1.33 $self->InsertObject('AttributeKey', { id => $id,
708 :     description => Tracer::UnEscape($description),
709 :     'relationship-name' => $tableName});
710 : parrello 1.13 Trace("Attribute $id stored.") if T(3);
711 :     # Get the group line.
712 :     my ($marker, @groups) = Tracer::GetLine($fh);
713 :     if (! defined($marker)) {
714 :     Confess("End of file found where group record expected.");
715 :     } elsif ($marker ne '#GROUPS') {
716 :     Confess("Group record not found after key record.");
717 :     } else {
718 :     $retVal->Add(memberships => scalar(@groups));
719 :     # Connect the groups.
720 :     for my $group (@groups) {
721 :     # Find out if this is a new group.
722 :     if (! $groups{$group}) {
723 :     $retVal->Add(newGroup => 1);
724 :     # Add the group.
725 :     $self->InsertObject('AttributeGroup', { id => $group });
726 :     Trace("Group $group created.") if T(3);
727 :     # Make sure we know it's not new.
728 :     $groups{$group} = 1;
729 :     }
730 :     # Connect the group to our key.
731 :     $self->InsertObject('IsInGroup', { 'from-link' => $id, 'to-link' => $group });
732 :     }
733 :     Trace("$id added to " . scalar(@groups) . " groups.") if T(3);
734 :     }
735 :     }
736 :     }
737 : parrello 1.18 # Log the operation.
738 :     $self->LogOperation("Backup Keys", $fileName, $retVal->Display());
739 : parrello 1.13 # Return the result.
740 :     return $retVal;
741 :     }
742 :    
743 : parrello 1.20 =head3 ArchiveFileName
744 :    
745 : parrello 1.31 my $fileName = $ca->ArchiveFileName();
746 : parrello 1.20
747 :     Compute a file name for archiving attribute input data. The file will be in the attribute log directory
748 :    
749 :     =cut
750 :    
751 :     sub ArchiveFileName {
752 :     # Get the parameters.
753 :     my ($self) = @_;
754 :     # Declare the return variable.
755 :     my $retVal;
756 :     # We start by turning the timestamp into something usable as a file name.
757 :     my $now = Tracer::Now();
758 :     $now =~ tr/ :\//___/;
759 :     # Next we get the directory name.
760 :     my $dir = "$FIG_Config::var/attributes";
761 :     if (! -e $dir) {
762 :     Trace("Creating attribute file directory $dir.") if T(1);
763 :     mkdir $dir;
764 :     }
765 :     # Put it together with the field name and the time stamp.
766 :     $retVal = "$dir/upload.$now";
767 :     # Modify the file name to insure it's unique.
768 :     my $seq = 0;
769 :     while (-e "$retVal.$seq.tbl") { $seq++ }
770 :     # Use the computed sequence number to get the correct file name.
771 :     $retVal .= ".$seq.tbl";
772 :     # Return the result.
773 :     return $retVal;
774 :     }
775 : parrello 1.13
776 : parrello 1.11 =head3 BackupAllAttributes
777 :    
778 : parrello 1.31 my $stats = $attrDB->BackupAllAttributes($fileName, %options);
779 : parrello 1.11
780 :     Backup all of the attributes to a file. The attributes will be stored in a
781 :     tab-delimited file suitable for reloading via L</LoadAttributesFrom>.
782 :    
783 :     =over 4
784 :    
785 :     =item fileName
786 :    
787 :     Name of the file to which the attribute data should be backed up.
788 :    
789 :     =item options
790 :    
791 :     Hash of options for the backup.
792 :    
793 :     =item RETURN
794 :    
795 :     Returns a statistics object describing the backup.
796 :    
797 :     =back
798 :    
799 :     Currently there are no options defined.
800 :    
801 :     =cut
802 :    
803 :     sub BackupAllAttributes {
804 :     # Get the parameters.
805 :     my ($self, $fileName, %options) = @_;
806 :     # Declare the return variable.
807 :     my $retVal = Stats->new();
808 :     # Get a list of the keys.
809 : parrello 1.33 my %keys = map { $_->[0] => $_->[1] } $self->GetAll(['AttributeKey'],
810 :     "", [], ['AttributeKey(id)',
811 :     'AttributeKey(relationship-name)']);
812 :     Trace(scalar(keys %keys) . " keys found during backup.") if T(2);
813 : parrello 1.11 # Open the file for output.
814 : parrello 1.12 my $fh = Open(undef, ">$fileName");
815 : parrello 1.11 # Loop through the keys.
816 : parrello 1.33 for my $key (sort keys %keys) {
817 : parrello 1.11 Trace("Backing up attribute $key.") if T(3);
818 :     $retVal->Add(keys => 1);
819 : parrello 1.33 # Get the key's relevant relationship name.
820 :     my $relName = $keys{$key};
821 : parrello 1.11 # Loop through this key's values.
822 : parrello 1.33 my $query = $self->Get([$relName], "$relName(from-link) = ?", [$key]);
823 : parrello 1.11 my $valuesFound = 0;
824 :     while (my $line = $query->Fetch()) {
825 :     $valuesFound++;
826 :     # Get this row's data.
827 : parrello 1.33 my ($id, $key, $subKey, $value) = $line->Values(["$relName(to-link)",
828 :     "$relName(from-link)",
829 :     "$relName(subkey)",
830 :     "$relName(value)"]);
831 : parrello 1.20 # Check for a subkey.
832 :     if ($subKey ne '') {
833 :     $key = "$key$self->{splitter}$subKey";
834 : parrello 1.31 }
835 : parrello 1.11 # Write it to the file.
836 : parrello 1.33 Tracer::PutLine($fh, [$id, $key, Escape($value)]);
837 : parrello 1.11 }
838 :     Trace("$valuesFound values backed up for key $key.") if T(3);
839 :     $retVal->Add(values => $valuesFound);
840 :     }
841 : parrello 1.18 # Log the operation.
842 :     $self->LogOperation("Backup Data", $fileName, $retVal->Display());
843 : parrello 1.11 # Return the result.
844 :     return $retVal;
845 :     }
846 :    
847 : parrello 1.1
848 : parrello 1.10 =head3 GetGroups
849 : parrello 1.3
850 : parrello 1.31 my @groups = $attrDB->GetGroups();
851 : parrello 1.3
852 : parrello 1.10 Return a list of the available groups.
853 : parrello 1.3
854 :     =cut
855 :    
856 : parrello 1.10 sub GetGroups {
857 : parrello 1.3 # Get the parameters.
858 : parrello 1.10 my ($self) = @_;
859 :     # Get the groups.
860 :     my @retVal = $self->GetFlat(['AttributeGroup'], "", [], 'AttributeGroup(id)');
861 :     # Return them.
862 :     return @retVal;
863 : parrello 1.3 }
864 :    
865 : parrello 1.10 =head3 GetAttributeData
866 : parrello 1.3
867 : parrello 1.31 my %keys = $attrDB->GetAttributeData($type, @list);
868 : parrello 1.3
869 : parrello 1.10 Return attribute data for the selected attributes. The attribute
870 :     data is a hash mapping each attribute key name to a n-tuple containing the
871 : parrello 1.33 data type, the description, the table name, and the groups.
872 : parrello 1.3
873 :     =over 4
874 :    
875 : parrello 1.10 =item type
876 : parrello 1.4
877 : parrello 1.10 Type of attribute criterion: C<name> for attributes whose names begin with the
878 :     specified string, or C<group> for attributes in the specified group.
879 : parrello 1.4
880 : parrello 1.10 =item list
881 : parrello 1.4
882 : parrello 1.10 List containing the names of the groups or keys for the desired attributes.
883 : parrello 1.4
884 :     =item RETURN
885 :    
886 : parrello 1.33 Returns a hash mapping each attribute key name to its description,
887 :     table name, and parent groups.
888 : parrello 1.4
889 :     =back
890 :    
891 :     =cut
892 :    
893 : parrello 1.10 sub GetAttributeData {
894 : parrello 1.4 # Get the parameters.
895 : parrello 1.10 my ($self, $type, @list) = @_;
896 :     # Set up a hash to store the attribute data.
897 :     my %retVal = ();
898 :     # Loop through the list items.
899 :     for my $item (@list) {
900 :     # Set up a query for the desired attributes.
901 :     my $query;
902 :     if ($type eq 'name') {
903 :     # Here we're doing a generic name search. We need to escape it and then tack
904 :     # on a %.
905 :     my $parm = $item;
906 :     $parm =~ s/_/\\_/g;
907 :     $parm =~ s/%/\\%/g;
908 :     $parm .= "%";
909 :     # Ask for matching attributes. (Note that if the user passed in a null string
910 :     # he'll get everything.)
911 :     $query = $self->Get(['AttributeKey'], "AttributeKey(id) LIKE ?", [$parm]);
912 :     } elsif ($type eq 'group') {
913 :     $query = $self->Get(['IsInGroup', 'AttributeKey'], "IsInGroup(to-link) = ?", [$item]);
914 : parrello 1.4 } else {
915 : parrello 1.10 Confess("Unknown attribute query type \"$type\".");
916 :     }
917 :     while (my $row = $query->Fetch()) {
918 :     # Get this attribute's data.
919 : parrello 1.33 my ($key, $relName, $notes) = $row->Values(['AttributeKey(id)',
920 :     'AttributeKey(relationship-name)',
921 : parrello 1.10 'AttributeKey(description)']);
922 :     # If it's new, get its groups and add it to the return hash.
923 :     if (! exists $retVal{$key}) {
924 :     my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(from-link) = ?",
925 :     [$key], 'IsInGroup(to-link)');
926 : parrello 1.33 $retVal{$key} = [$relName, $notes, @groups];
927 : parrello 1.4 }
928 :     }
929 :     }
930 :     # Return the result.
931 : parrello 1.10 return %retVal;
932 : parrello 1.4 }
933 :    
934 : parrello 1.18 =head3 LogOperation
935 :    
936 : parrello 1.31 $ca->LogOperation($action, $target, $description);
937 : parrello 1.18
938 :     Write an operation description to the attribute activity log (C<$FIG_Config::var/attributes.log>).
939 :    
940 :     =over 4
941 :    
942 :     =item action
943 :    
944 :     Action being logged (e.g. C<Delete Group> or C<Load Key>).
945 :    
946 :     =item target
947 :    
948 :     ID of the key or group affected.
949 :    
950 :     =item description
951 :    
952 :     Short description of the action.
953 :    
954 :     =back
955 :    
956 :     =cut
957 :    
958 :     sub LogOperation {
959 :     # Get the parameters.
960 :     my ($self, $action, $target, $description) = @_;
961 :     # Get the user ID.
962 :     my $user = $self->{user};
963 :     # Get a timestamp.
964 :     my $timeString = Tracer::Now();
965 :     # Open the log file for appending.
966 :     my $oh = Open(undef, ">>$FIG_Config::var/attributes.log");
967 :     # Write the data to it.
968 :     Tracer::PutLine($oh, [$timeString, $user, $action, $target, $description]);
969 :     # Close the log file.
970 :     close $oh;
971 :     }
972 :    
973 : parrello 1.3 =head2 FIG Method Replacements
974 :    
975 :     The following methods are used by B<FIG.pm> to replace the previous attribute functionality.
976 : parrello 1.10 Some of the old functionality is no longer present: controlled vocabulary is no longer
977 : parrello 1.3 supported and there is no longer any searching by URL. Fortunately, neither of these
978 :     capabilities were used in the old system.
979 :    
980 : parrello 1.4 The methods here are the only ones supported by the B<RemoteCustomAttributes> object.
981 :     The idea is that these methods represent attribute manipulation allowed by all users, while
982 :     the others are only for privileged users with access to the attribute server.
983 :    
984 : parrello 1.20 In the previous implementation, an attribute had a value and a URL. In this implementation,
985 :     each attribute has only a value. These methods will treat the value as a list with the individual
986 :     elements separated by the value of the splitter parameter on the constructor (L</new>). The default
987 :     is double colons C<::>.
988 : parrello 1.3
989 : parrello 1.10 So, for example, an old-style keyword with a value of C<essential> and a URL of
990 : parrello 1.3 C<http://www.sciencemag.org/cgi/content/abstract/293/5538/2266> using the default
991 :     splitter value would be stored as
992 :    
993 :     essential::http://www.sciencemag.org/cgi/content/abstract/293/5538/2266
994 :    
995 :     The best performance is achieved by searching for a particular key for a specified
996 :     feature or genome.
997 :    
998 :     =head3 GetAttributes
999 :    
1000 : parrello 1.31 my @attributeList = $attrDB->GetAttributes($objectID, $key, @values);
1001 : parrello 1.3
1002 :     In the database, attribute values are sectioned into pieces using a splitter
1003 :     value specified in the constructor (L</new>). This is not a requirement of
1004 :     the attribute system as a whole, merely a convenience for the purpose of
1005 : parrello 1.10 these methods. If a value has multiple sections, each section
1006 :     is matched against the corresponding criterion in the I<@valuePatterns> list.
1007 : parrello 1.3
1008 :     This method returns a series of tuples that match the specified criteria. Each tuple
1009 :     will contain an object ID, a key, and one or more values. The parameters to this
1010 : parrello 1.10 method therefore correspond structurally to the values expected in each tuple. In
1011 :     addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
1012 :     of the parameters. So, for example,
1013 : parrello 1.3
1014 : parrello 1.10 my @attributeList = $attrDB->GetAttributes('fig|100226.1.peg.1004', 'structure%', 1, 2);
1015 : parrello 1.3
1016 :     would return something like
1017 :    
1018 :     ['fig}100226.1.peg.1004', 'structure', 1, 2]
1019 :     ['fig}100226.1.peg.1004', 'structure1', 1, 2]
1020 :     ['fig}100226.1.peg.1004', 'structure2', 1, 2]
1021 :     ['fig}100226.1.peg.1004', 'structureA', 1, 2]
1022 :    
1023 : parrello 1.10 Use of C<undef> in any position acts as a wild card (all values). You can also specify
1024 :     a list reference in the ID column. Thus,
1025 :    
1026 :     my @attributeList = $attrDB->GetAttributes(['100226.1', 'fig|100226.1.%'], 'PUBMED');
1027 :    
1028 :     would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
1029 :     features.
1030 : parrello 1.3
1031 :     In addition to values in multiple sections, a single attribute key can have multiple
1032 :     values, so even
1033 :    
1034 : parrello 1.10 my @attributeList = $attrDB->GetAttributes($peg, 'virulent');
1035 : parrello 1.3
1036 :     which has no wildcard in the key or the object ID, may return multiple tuples.
1037 :    
1038 : parrello 1.10 Value matching in this system works very poorly, because of the way multiple values are
1039 : parrello 1.20 stored. For the object ID, key name, and first value, we create queries that filter for the
1040 :     desired results. On any filtering by value, we must do a comparison after the attributes are
1041 :     retrieved from the database, since the database has no notion of the multiple values, which
1042 :     are stored in a single string. As a result, queries in which filter only on value end up
1043 :     reading a lot more than they need to.
1044 : parrello 1.3
1045 :     =over 4
1046 :    
1047 :     =item objectID
1048 :    
1049 : parrello 1.10 ID of object whose attributes are desired. If the attributes are desired for multiple
1050 :     objects, this parameter can be specified as a list reference. If the attributes are
1051 :     desired for all objects, specify C<undef> or an empty string. Finally, you can specify
1052 :     attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
1053 : parrello 1.3
1054 :     =item key
1055 :    
1056 : parrello 1.10 Attribute key name. A value of C<undef> or an empty string will match all
1057 :     attribute keys. If the values are desired for multiple keys, this parameter can be
1058 :     specified as a list reference. Finally, you can specify attributes for a range of
1059 :     keys by putting a percent sign (C<%>) at the end.
1060 : parrello 1.3
1061 : parrello 1.10 =item values
1062 : parrello 1.3
1063 :     List of the desired attribute values, section by section. If C<undef>
1064 : parrello 1.10 or an empty string is specified, all values in that section will match. A
1065 :     generic match can be requested by placing a percent sign (C<%>) at the end.
1066 :     In that case, all values that match up to and not including the percent sign
1067 : parrello 1.14 will match. You may also specify a regular expression enclosed
1068 :     in slashes. All values that match the regular expression will be returned. For
1069 :     performance reasons, only values have this extra capability.
1070 : parrello 1.3
1071 :     =item RETURN
1072 :    
1073 :     Returns a list of tuples. The first element in the tuple is an object ID, the
1074 :     second is an attribute key, and the remaining elements are the sections of
1075 :     the attribute value. All of the tuples will match the criteria set forth in
1076 :     the parameter list.
1077 :    
1078 :     =back
1079 :    
1080 :     =cut
1081 :    
1082 :     sub GetAttributes {
1083 : parrello 1.4 # Get the parameters.
1084 : parrello 1.10 my ($self, $objectID, $key, @values) = @_;
1085 : parrello 1.38 # Declare the return variable.
1086 :     my @retVal = ();
1087 :     # Insure we have at least some sort of filtering going on.
1088 :     if (! grep { defined $_ } $objectID, $key, @values) {
1089 :     Confess("No filters specified in GetAttributes call.");
1090 :     } else {
1091 :     # This hash will map value-table fields to patterns. We use it to build the
1092 :     # SQL statement.
1093 :     my %data;
1094 :     # Add the object ID to the key information.
1095 :     $data{'to-link'} = $objectID;
1096 :     # The first value represents a problem, because we can search it using SQL, but not
1097 :     # in the normal way. If the user specifies a generic search or exact match for
1098 :     # every alternative value (remember, the values may be specified as a list),
1099 :     # then we can create SQL filtering for it. If any of the values are specified
1100 :     # as a regular expression, however, that's more complicated, because
1101 :     # we need to read every value to verify a match.
1102 : parrello 1.39 if (@values > 0 && defined $values[0]) {
1103 : parrello 1.38 # Get the first value and put its alternatives in an array.
1104 :     my $valueParm = $values[0];
1105 :     my @valueList;
1106 :     if (ref $valueParm eq 'ARRAY') {
1107 :     @valueList = @{$valueParm};
1108 : parrello 1.20 } else {
1109 : parrello 1.38 @valueList = ($valueParm);
1110 : parrello 1.20 }
1111 : parrello 1.38 # Okay, now we have all the possible criteria for the first value in the list
1112 :     # @valueList. We'll copy the values to a new array in which they have been
1113 :     # converted to generic requests. If we find a regular-expression match
1114 :     # anywhere in the list, we toss the whole thing.
1115 :     my @valuePatterns = ();
1116 :     my $okValues = 1;
1117 :     for my $valuePattern (@valueList) {
1118 :     # Check the pattern type.
1119 :     if (substr($valuePattern, 0, 1) eq '/') {
1120 :     # Regular expressions invalidate the entire process.
1121 :     $okValues = 0;
1122 :     } elsif (substr($valuePattern, -1, 1) eq '%') {
1123 :     # A Generic pattern is passed in unmodified.
1124 :     push @valuePatterns, $valuePattern;
1125 :     } else {
1126 :     # An exact match is converted to generic.
1127 :     push @valuePatterns, "$valuePattern%";
1128 : parrello 1.33 }
1129 :     }
1130 : parrello 1.38 # If everything works, add the value data to the filtering hash.
1131 :     if ($okValues) {
1132 :     $data{value} = \@valuePatterns;
1133 : parrello 1.33 }
1134 : parrello 1.38 }
1135 :     # Now comes the really tricky part, which is key handling. The key is
1136 :     # actually split in two parts: the real key and a sub-key. The real key
1137 :     # determines which value table contains the relevant values. The information
1138 :     # we need is kept in here.
1139 :     my %tables = map { $_ => [] } $self->_GetAllTables();
1140 :     # See if we have any key filtering to worry about.
1141 :     if ($key) {
1142 :     # Here we have either a single key or a list. We convert both cases to a list.
1143 :     my $keyList = (ref $key ne 'ARRAY' ? [$key] : $key);
1144 : parrello 1.40 Trace("Reading key table.") if T(3);
1145 : parrello 1.38 # Get easy access to the key/table hash.
1146 :     my $keyTableHash = $self->_KeyTable();
1147 :     # Loop through the keys, discovering tables.
1148 :     for my $keyChoice (@$keyList) {
1149 :     # Now we have to start thinking about the real key and the subkeys.
1150 :     my ($realKey, $subKey) = $self->_SplitKeyPattern($keyChoice);
1151 : parrello 1.40 Trace("Checking $realKey against key table.") if T(3);
1152 : parrello 1.38 # Find the matches for the real key in the key hash. For each of
1153 :     # these, we memorize the table name in the hash below.
1154 :     my %tableNames = ();
1155 :     for my $keyInTable (keys %{$keyTableHash}) {
1156 : parrello 1.40 if (_CheckSQLPattern($realKey, $keyInTable)) {
1157 : parrello 1.38 $tableNames{$keyTableHash->{$key}} = 1;
1158 :     }
1159 :     }
1160 :     # If the key is generic, or didn't match anything, add
1161 :     # the default table to the mix.
1162 :     if (keys %tableNames == 0 || $keyChoice =~ /%/) {
1163 :     $tableNames{$self->{defaultRel}} = 1;
1164 :     }
1165 :     # Now we add this key combination to the key list for each relevant table.
1166 :     for my $tableName (keys %tableNames) {
1167 :     push @{$tables{$tableName}}, [$realKey, $subKey];
1168 :     }
1169 : parrello 1.33 }
1170 : parrello 1.20 }
1171 : parrello 1.38 # Now we loop through the tables of interest, performing queries.
1172 :     # Loop through the tables.
1173 :     for my $table (keys %tables) {
1174 :     # Get the key pairs for this table.
1175 :     my $pairs = $tables{$table};
1176 :     # Does this table have data? It does if there is no key specified or
1177 :     # it has at least one key pair.
1178 :     my $pairCount = scalar @{$pairs};
1179 :     Trace("Pair count for table $table is $pairCount.") if T(3);
1180 :     if ($pairCount || ! $key) {
1181 :     # Create some lists to contain the filter fragments and parameter values.
1182 :     my @filter = ();
1183 :     my @parms = ();
1184 :     # This next loop goes through the different fields that can be specified in the
1185 :     # parameter list and generates filters for each. The %data hash that we built above
1186 :     # contains most of the necessary information to do this. When we're done, we'll
1187 :     # paste on stuff for the key pairs.
1188 :     for my $field (keys %data) {
1189 :     # Accumulate filter information for this field. We will OR together all the
1190 :     # elements accumulated to create the final result.
1191 :     my @fieldFilter = ();
1192 :     # Get the specified filter for this field.
1193 :     my $fieldPattern = $data{$field};
1194 :     # Only proceed if the pattern is one that won't match everything.
1195 :     if (defined($fieldPattern) && $fieldPattern ne "" && $fieldPattern ne "%") {
1196 :     # Convert the pattern to an array.
1197 :     my @patterns = ();
1198 :     if (ref $fieldPattern eq 'ARRAY') {
1199 :     push @patterns, @{$fieldPattern};
1200 :     } else {
1201 :     push @patterns, $fieldPattern;
1202 :     }
1203 :     # Only proceed if the array is nonempty. The loop will work fine if the
1204 :     # array is empty, but when we build the filter string at the end we'll
1205 :     # get "()" in the filter list, which will result in an SQL syntax error.
1206 :     if (@patterns) {
1207 :     # Loop through the individual patterns.
1208 :     for my $pattern (@patterns) {
1209 :     my ($clause, $value) = _WherePart($table, $field, $pattern);
1210 :     push @fieldFilter, $clause;
1211 :     push @parms, $value;
1212 :     }
1213 :     # Form the filter for this field.
1214 :     my $fieldFilterString = join(" OR ", @fieldFilter);
1215 :     push @filter, "($fieldFilterString)";
1216 : parrello 1.33 }
1217 :     }
1218 :     }
1219 : parrello 1.38 # The final filter is for the key pairs. Only proceed if we have some.
1220 :     if ($pairCount) {
1221 :     # We'll accumulate pair filter clauses in here.
1222 :     my @pairFilters = ();
1223 :     # Loop through the key pairs.
1224 :     for my $pair (@$pairs) {
1225 :     my ($realKey, $subKey) = @{$pair};
1226 :     my ($realClause, $realValue) = _WherePart($table, 'from-link', $realKey);
1227 :     if (! $subKey) {
1228 :     # Here the subkey is wild, so only the real key matters.
1229 :     push @pairFilters, $realClause;
1230 :     push @parms, $realValue;
1231 :     } else {
1232 :     # Here we have to select on both keys.
1233 :     my ($subClause, $subValue) = _WherePart($table, 'subkey', $subKey);
1234 :     push @pairFilters, "($realClause AND $subClause)";
1235 :     push @parms, $realValue, $subValue;
1236 :     }
1237 : parrello 1.10 }
1238 : parrello 1.38 # Join the pair filters together to make a giant key filter.
1239 :     my $pairFilter = "(" . join(" OR ", @pairFilters) . ")";
1240 :     push @filter, $pairFilter;
1241 : parrello 1.10 }
1242 : parrello 1.38 # At this point, @filter contains one or more filter strings and @parms
1243 :     # contains the parameter values to bind to them.
1244 :     my $actualFilter = join(" AND ", @filter);
1245 :     # Now we're ready to make our query.
1246 :     my $query = $self->Get([$table], $actualFilter, \@parms);
1247 :     # Format the results.
1248 :     push @retVal, $self->_QueryResults($query, $table, @values);
1249 : parrello 1.10 }
1250 :     }
1251 :     }
1252 : parrello 1.33 # The above loop ran the query for each necessary value table and merged the
1253 :     # results into @retVal. Now we return the rows found.
1254 : parrello 1.3 return @retVal;
1255 :     }
1256 :    
1257 :     =head3 AddAttribute
1258 :    
1259 : parrello 1.31 $attrDB->AddAttribute($objectID, $key, @values);
1260 : parrello 1.3
1261 :     Add an attribute key/value pair to an object. This method cannot add a new key, merely
1262 :     add a value to an existing key. Use L</StoreAttributeKey> to create a new key.
1263 :    
1264 :     =over 4
1265 :    
1266 :     =item objectID
1267 :    
1268 : parrello 1.10 ID of the object to which the attribute is to be added.
1269 : parrello 1.3
1270 :     =item key
1271 :    
1272 : parrello 1.10 Attribute key name.
1273 : parrello 1.3
1274 :     =item values
1275 :    
1276 :     One or more values to be associated with the key. The values are joined together with
1277 :     the splitter value before being stored as field values. This enables L</GetAttributes>
1278 :     to split them apart during retrieval. The splitter value defaults to double colons C<::>.
1279 :    
1280 :     =back
1281 :    
1282 :     =cut
1283 :    
1284 :     sub AddAttribute {
1285 :     # Get the parameters.
1286 : parrello 1.4 my ($self, $objectID, $key, @values) = @_;
1287 : parrello 1.3 # Don't allow undefs.
1288 :     if (! defined($objectID)) {
1289 :     Confess("No object ID specified for AddAttribute call.");
1290 :     } elsif (! defined($key)) {
1291 :     Confess("No attribute key specified for AddAttribute call.");
1292 :     } elsif (! @values) {
1293 :     Confess("No values specified in AddAttribute call for key $key.");
1294 :     } else {
1295 : parrello 1.11 # Okay, now we have some reason to believe we can do this. Form the values
1296 :     # into a scalar.
1297 : parrello 1.3 my $valueString = join($self->{splitter}, @values);
1298 : parrello 1.20 # Split up the key.
1299 :     my ($realKey, $subKey) = $self->SplitKey($key);
1300 : parrello 1.33 # Find the table containing the key.
1301 :     my $table = $self->_KeyTable($realKey);
1302 : parrello 1.11 # Connect the object to the key.
1303 : parrello 1.33 $self->InsertObject($table, { 'from-link' => $realKey,
1304 : parrello 1.11 'to-link' => $objectID,
1305 : parrello 1.20 'subkey' => $subKey,
1306 : parrello 1.11 'value' => $valueString,
1307 :     });
1308 : parrello 1.3 }
1309 : parrello 1.10 # Return a one, indicating success. We do this for backward compatability.
1310 : parrello 1.3 return 1;
1311 :     }
1312 :    
1313 :     =head3 DeleteAttribute
1314 :    
1315 : parrello 1.31 $attrDB->DeleteAttribute($objectID, $key, @values);
1316 : parrello 1.3
1317 :     Delete the specified attribute key/value combination from the database.
1318 :    
1319 :     =over 4
1320 :    
1321 :     =item objectID
1322 :    
1323 : parrello 1.10 ID of the object whose attribute is to be deleted.
1324 : parrello 1.3
1325 :     =item key
1326 :    
1327 : parrello 1.10 Attribute key name.
1328 : parrello 1.3
1329 :     =item values
1330 :    
1331 : parrello 1.10 One or more values associated with the key. If no values are specified, then all values
1332 :     will be deleted. Otherwise, only a matching value will be deleted.
1333 : parrello 1.3
1334 :     =back
1335 :    
1336 :     =cut
1337 :    
1338 :     sub DeleteAttribute {
1339 :     # Get the parameters.
1340 : parrello 1.4 my ($self, $objectID, $key, @values) = @_;
1341 : parrello 1.3 # Don't allow undefs.
1342 :     if (! defined($objectID)) {
1343 :     Confess("No object ID specified for DeleteAttribute call.");
1344 :     } elsif (! defined($key)) {
1345 :     Confess("No attribute key specified for DeleteAttribute call.");
1346 :     } else {
1347 : parrello 1.20 # Split the key into the real key and the subkey.
1348 :     my ($realKey, $subKey) = $self->SplitKey($key);
1349 : parrello 1.33 # Find the table containing the key's values.
1350 :     my $table = $self->_KeyTable($realKey);
1351 : parrello 1.20 if ($subKey eq '' && scalar(@values) == 0) {
1352 :     # Here we erase the entire key for this object.
1353 :     $self->DeleteRow('HasValueFor', $key, $objectID);
1354 :     } else {
1355 :     # Here we erase the matching values.
1356 :     my $valueString = join($self->{splitter}, @values);
1357 :     $self->DeleteRow('HasValueFor', $realKey, $objectID,
1358 :     { subkey => $subKey, value => $valueString });
1359 :     }
1360 : parrello 1.3 }
1361 :     # Return a one. This is for backward compatability.
1362 :     return 1;
1363 :     }
1364 :    
1365 : parrello 1.16 =head3 DeleteMatchingAttributes
1366 :    
1367 : parrello 1.31 my @deleted = $attrDB->DeleteMatchingAttributes($objectID, $key, @values);
1368 : parrello 1.16
1369 :     Delete all attributes that match the specified criteria. This is equivalent to
1370 :     calling L</GetAttributes> and then invoking L</DeleteAttribute> for each
1371 :     row found.
1372 :    
1373 :     =over 4
1374 :    
1375 :     =item objectID
1376 :    
1377 :     ID of object whose attributes are to be deleted. If the attributes for multiple
1378 :     objects are to be deleted, this parameter can be specified as a list reference. If
1379 :     attributes are to be deleted for all objects, specify C<undef> or an empty string.
1380 :     Finally, you can delete attributes for a range of object IDs by putting a percent
1381 :     sign (C<%>) at the end.
1382 :    
1383 :     =item key
1384 :    
1385 :     Attribute key name. A value of C<undef> or an empty string will match all
1386 :     attribute keys. If the values are to be deletedfor multiple keys, this parameter can be
1387 :     specified as a list reference. Finally, you can delete attributes for a range of
1388 :     keys by putting a percent sign (C<%>) at the end.
1389 :    
1390 :     =item values
1391 :    
1392 :     List of the desired attribute values, section by section. If C<undef>
1393 :     or an empty string is specified, all values in that section will match. A
1394 :     generic match can be requested by placing a percent sign (C<%>) at the end.
1395 :     In that case, all values that match up to and not including the percent sign
1396 :     will match. You may also specify a regular expression enclosed
1397 :     in slashes. All values that match the regular expression will be deleted. For
1398 :     performance reasons, only values have this extra capability.
1399 :    
1400 :     =item RETURN
1401 :    
1402 :     Returns a list of tuples for the attributes that were deleted, in the
1403 :     same form as L</GetAttributes>.
1404 :    
1405 :     =back
1406 :    
1407 :     =cut
1408 :    
1409 :     sub DeleteMatchingAttributes {
1410 :     # Get the parameters.
1411 :     my ($self, $objectID, $key, @values) = @_;
1412 :     # Get the matching attributes.
1413 :     my @retVal = $self->GetAttributes($objectID, $key, @values);
1414 :     # Loop through the attributes, deleting them.
1415 :     for my $tuple (@retVal) {
1416 :     $self->DeleteAttribute(@{$tuple});
1417 :     }
1418 : parrello 1.18 # Log this operation.
1419 :     my $count = @retVal;
1420 :     $self->LogOperation("Mass Delete", $key, "$count matching attributes deleted.");
1421 : parrello 1.16 # Return the deleted attributes.
1422 :     return @retVal;
1423 :     }
1424 :    
1425 : parrello 1.3 =head3 ChangeAttribute
1426 :    
1427 : parrello 1.31 $attrDB->ChangeAttribute($objectID, $key, \@oldValues, \@newValues);
1428 : parrello 1.3
1429 :     Change the value of an attribute key/value pair for an object.
1430 :    
1431 :     =over 4
1432 :    
1433 :     =item objectID
1434 :    
1435 :     ID of the genome or feature to which the attribute is to be changed. In general, an ID that
1436 :     starts with C<fig|> is treated as a feature ID, and an ID that is all digits and periods
1437 :     is treated as a genome ID. For IDs of other types, this parameter should be a reference
1438 :     to a 2-tuple consisting of the entity type name followed by the object ID.
1439 :    
1440 :     =item key
1441 :    
1442 :     Attribute key name. This corresponds to the name of a field in the database.
1443 :    
1444 :     =item oldValues
1445 :    
1446 :     One or more values identifying the key/value pair to change.
1447 :    
1448 :     =item newValues
1449 :    
1450 :     One or more values to be put in place of the old values.
1451 :    
1452 :     =back
1453 :    
1454 :     =cut
1455 :    
1456 :     sub ChangeAttribute {
1457 :     # Get the parameters.
1458 : parrello 1.4 my ($self, $objectID, $key, $oldValues, $newValues) = @_;
1459 : parrello 1.3 # Don't allow undefs.
1460 :     if (! defined($objectID)) {
1461 :     Confess("No object ID specified for ChangeAttribute call.");
1462 :     } elsif (! defined($key)) {
1463 :     Confess("No attribute key specified for ChangeAttribute call.");
1464 :     } elsif (! defined($oldValues) || ref $oldValues ne 'ARRAY') {
1465 :     Confess("No old values specified in ChangeAttribute call for key $key.");
1466 :     } elsif (! defined($newValues) || ref $newValues ne 'ARRAY') {
1467 :     Confess("No new values specified in ChangeAttribute call for key $key.");
1468 :     } else {
1469 : parrello 1.10 # We do the change as a delete/add.
1470 : parrello 1.3 $self->DeleteAttribute($objectID, $key, @{$oldValues});
1471 :     $self->AddAttribute($objectID, $key, @{$newValues});
1472 :     }
1473 :     # Return a one. We do this for backward compatability.
1474 :     return 1;
1475 :     }
1476 :    
1477 : parrello 1.7 =head3 EraseAttribute
1478 :    
1479 : parrello 1.31 $attrDB->EraseAttribute($key);
1480 : parrello 1.7
1481 :     Erase all values for the specified attribute key. This does not remove the
1482 :     key from the database; it merely removes all the values.
1483 :    
1484 :     =over 4
1485 :    
1486 :     =item key
1487 :    
1488 : parrello 1.20 Key to erase. This must be a real key; that is, it cannot have a subkey
1489 :     component.
1490 : parrello 1.7
1491 :     =back
1492 :    
1493 :     =cut
1494 :    
1495 :     sub EraseAttribute {
1496 :     # Get the parameters.
1497 : parrello 1.10 my ($self, $key) = @_;
1498 : parrello 1.33 # Find the table containing the key.
1499 :     my $table = $self->_KeyTable($key);
1500 :     # Is it the default table?
1501 :     if ($table eq $self->{defaultRel}) {
1502 :     # Yes, so the key is mixed in with other keys.
1503 :     # Delete everything connected to it.
1504 :     $self->Disconnect('HasValueFor', 'AttributeKey', $key);
1505 :     } else {
1506 :     # No. Drop and re-create the table.
1507 :     $self->TruncateTable($table);
1508 :     }
1509 : parrello 1.18 # Log the operation.
1510 :     $self->LogOperation("Erase Data", $key);
1511 : parrello 1.7 # Return a 1, for backward compatability.
1512 :     return 1;
1513 :     }
1514 :    
1515 : parrello 1.9 =head3 GetAttributeKeys
1516 :    
1517 : parrello 1.31 my @keyList = $attrDB->GetAttributeKeys($groupName);
1518 : parrello 1.9
1519 : parrello 1.10 Return a list of the attribute keys for a particular group.
1520 : parrello 1.9
1521 :     =over 4
1522 :    
1523 : parrello 1.10 =item groupName
1524 : parrello 1.9
1525 : parrello 1.10 Name of the group whose keys are desired.
1526 : parrello 1.9
1527 :     =item RETURN
1528 :    
1529 : parrello 1.10 Returns a list of the attribute keys for the specified group.
1530 : parrello 1.9
1531 :     =back
1532 :    
1533 :     =cut
1534 :    
1535 :     sub GetAttributeKeys {
1536 :     # Get the parameters.
1537 : parrello 1.10 my ($self, $groupName) = @_;
1538 :     # Get the attributes for the specified group.
1539 :     my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(to-link) = ?", [$groupName],
1540 :     'IsInGroup(from-link)');
1541 : parrello 1.9 # Return the keys.
1542 : parrello 1.10 return sort @groups;
1543 : parrello 1.9 }
1544 :    
1545 : parrello 1.24 =head3 QueryAttributes
1546 :    
1547 : parrello 1.31 my @attributeData = $ca->QueryAttributes($filter, $filterParms);
1548 : parrello 1.24
1549 :     Return the attribute data based on an SQL filter clause. In the filter clause,
1550 :     the name C<$object> should be used for the object ID, C<$key> should be used for
1551 :     the key name, C<$subkey> for the subkey value, and C<$value> for the value field.
1552 :    
1553 :     =over 4
1554 :    
1555 :     =item filter
1556 :    
1557 :     Filter clause in the standard ERDB format, except that the field names are C<$object> for
1558 :     the object ID field, C<$key> for the key name field, C<$subkey> for the subkey field,
1559 :     and C<$value> for the value field. This abstraction enables us to hide the details of
1560 :     the database construction from the user.
1561 :    
1562 :     =item filterParms
1563 :    
1564 :     Parameters for the filter clause.
1565 :    
1566 :     =item RETURN
1567 :    
1568 :     Returns a list of tuples. Each tuple consists of an object ID, a key (with optional subkey), and
1569 :     one or more attribute values.
1570 :    
1571 :     =back
1572 :    
1573 :     =cut
1574 :    
1575 :     # This hash is used to drive the substitution process.
1576 : parrello 1.33 my %AttributeParms = (object => 'to-link',
1577 :     key => 'from-link',
1578 :     subkey => 'subkey',
1579 :     value => 'value');
1580 : parrello 1.24
1581 :     sub QueryAttributes {
1582 :     # Get the parameters.
1583 :     my ($self, $filter, $filterParms) = @_;
1584 :     # Declare the return variable.
1585 :     my @retVal = ();
1586 :     # Make sue we have filter parameters.
1587 :     my $realParms = (defined($filterParms) ? $filterParms : []);
1588 : parrello 1.33 # Loop through all the value tables.
1589 :     for my $table ($self->_GetAllTables()) {
1590 :     # Create the query for this table by converting the filter.
1591 :     my $realFilter = $filter;
1592 :     for my $name (keys %AttributeParms) {
1593 :     $realFilter =~ s/\$$name/$table($AttributeParms{$name})/g;
1594 :     }
1595 :     my $query = $self->Get([$table], $realFilter, $realParms);
1596 :     # Loop through the results, forming the output attribute tuples.
1597 :     while (my $result = $query->Fetch()) {
1598 :     # Get the four values from this query result row.
1599 :     my ($objectID, $key, $subkey, $value) = $result->Values(["$table($AttributeParms{object})",
1600 :     "$table($AttributeParms{key})",
1601 :     "$table($AttributeParms{subkey})",
1602 :     "$table($AttributeParms{value})"]);
1603 :     # Combine the key and the subkey.
1604 :     my $realKey = ($subkey ? $key . $self->{splitter} . $subkey : $key);
1605 :     # Split the value.
1606 :     my @values = split $self->{splitter}, $value;
1607 :     # Output the result.
1608 :     push @retVal, [$objectID, $realKey, @values];
1609 :     }
1610 : parrello 1.24 }
1611 :     # Return the result.
1612 :     return @retVal;
1613 :     }
1614 :    
1615 : parrello 1.20 =head2 Key and ID Manipulation Methods
1616 :    
1617 : parrello 1.19 =head3 ParseID
1618 :    
1619 : parrello 1.31 my ($type, $id) = CustomAttributes::ParseID($idValue);
1620 : parrello 1.19
1621 :     Determine the type and object ID corresponding to an ID value from the attribute database.
1622 :     Most ID values consist of a type name and an ID, separated by a colon (e.g. C<Family:aclame|cluster10>);
1623 :     however, Genomes, Features, and Subsystems are not stored with a type name, so we need to
1624 :     deduce the type from the ID value structure.
1625 :    
1626 :     The theory here is that you can plug the ID and type directly into a Sprout database method, as
1627 :     follows
1628 :    
1629 :     my ($type, $id) = CustomAttributes::ParseID($attrList[$num]->[0]);
1630 :     my $target = $sprout->GetEntity($type, $id);
1631 :    
1632 :     =over 4
1633 :    
1634 :     =item idValue
1635 :    
1636 :     ID value taken from the attribute database.
1637 :    
1638 :     =item RETURN
1639 :    
1640 :     Returns a two-element list. The first element is the type of object indicated by the ID value,
1641 :     and the second element is the actual object ID.
1642 :    
1643 :     =back
1644 :    
1645 :     =cut
1646 :    
1647 :     sub ParseID {
1648 :     # Get the parameters.
1649 :     my ($idValue) = @_;
1650 :     # Declare the return variables.
1651 :     my ($type, $id);
1652 :     # Parse the incoming ID. We first check for the presence of an entity name. Entity names
1653 :     # can only contain letters, which helps to insure typed object IDs don't collide with
1654 :     # subsystem names (which are untyped).
1655 :     if ($idValue =~ /^([A-Za-z]+):(.+)/) {
1656 :     # Here we have a typed ID.
1657 :     ($type, $id) = ($1, $2);
1658 : parrello 1.26 # Fix the case sensitivity on PDB IDs.
1659 :     if ($type eq 'PDB') { $id = lc $id; }
1660 : parrello 1.19 } elsif ($idValue =~ /fig\|/) {
1661 :     # Here we have a feature ID.
1662 :     ($type, $id) = (Feature => $idValue);
1663 :     } elsif ($idValue =~ /\d+\.\d+/) {
1664 :     # Here we have a genome ID.
1665 :     ($type, $id) = (Genome => $idValue);
1666 :     } else {
1667 :     # The default is a subsystem ID.
1668 :     ($type, $id) = (Subsystem => $idValue);
1669 :     }
1670 :     # Return the results.
1671 :     return ($type, $id);
1672 :     }
1673 :    
1674 :     =head3 FormID
1675 :    
1676 : parrello 1.31 my $idValue = CustomAttributes::FormID($type, $id);
1677 : parrello 1.19
1678 :     Convert an object type and ID pair into an object ID string for the attribute system. Subsystems,
1679 :     genomes, and features are stored in the database without type information, but all other object IDs
1680 :     must be prefixed with the object type.
1681 :    
1682 :     =over 4
1683 :    
1684 :     =item type
1685 :    
1686 :     Relevant object type.
1687 :    
1688 :     =item id
1689 :    
1690 :     ID of the object in question.
1691 :    
1692 :     =item RETURN
1693 :    
1694 :     Returns a string that will be recognized as an object ID in the attribute database.
1695 :    
1696 :     =back
1697 :    
1698 :     =cut
1699 :    
1700 :     sub FormID {
1701 :     # Get the parameters.
1702 :     my ($type, $id) = @_;
1703 :     # Declare the return variable.
1704 :     my $retVal;
1705 :     # Compute the ID string from the type.
1706 :     if (grep { $type eq $_ } qw(Feature Genome Subsystem)) {
1707 :     $retVal = $id;
1708 :     } else {
1709 :     $retVal = "$type:$id";
1710 :     }
1711 :     # Return the result.
1712 :     return $retVal;
1713 :     }
1714 :    
1715 :     =head3 GetTargetObject
1716 :    
1717 : parrello 1.31 my $object = CustomAttributes::GetTargetObject($erdb, $idValue);
1718 : parrello 1.19
1719 :     Return the database object corresponding to the specified attribute object ID. The
1720 :     object type associated with the ID value must correspond to an entity name in the
1721 :     specified database.
1722 :    
1723 :     =over 4
1724 :    
1725 :     =item erdb
1726 :    
1727 :     B<ERDB> object for accessing the target database.
1728 :    
1729 :     =item idValue
1730 :    
1731 :     ID value retrieved from the attribute database.
1732 :    
1733 :     =item RETURN
1734 :    
1735 : parrello 1.22 Returns a B<ERDBObject> for the attribute value's target object.
1736 : parrello 1.19
1737 :     =back
1738 :    
1739 :     =cut
1740 :    
1741 :     sub GetTargetObject {
1742 :     # Get the parameters.
1743 :     my ($erdb, $idValue) = @_;
1744 :     # Declare the return variable.
1745 :     my $retVal;
1746 :     # Get the type and ID for the target object.
1747 :     my ($type, $id) = ParseID($idValue);
1748 :     # Plug them into the GetEntity method.
1749 :     $retVal = $erdb->GetEntity($type, $id);
1750 :     # Return the resulting object.
1751 :     return $retVal;
1752 :     }
1753 :    
1754 : parrello 1.20 =head3 SplitKey
1755 :    
1756 : parrello 1.31 my ($realKey, $subKey) = $ca->SplitKey($key);
1757 : parrello 1.20
1758 :     Split an external key (that is, one passed in by a caller) into the real key and the sub key.
1759 :     The real and sub keys are separated by a splitter value (usually C<::>). If there is no splitter,
1760 :     then the sub key is presumed to be an empty string.
1761 :    
1762 :     =over 4
1763 :    
1764 :     =item key
1765 :    
1766 :     Incoming key to be split.
1767 :    
1768 :     =item RETURN
1769 :    
1770 :     Returns a two-element list, the first element of which is the real key and the second element of
1771 :     which is the sub key.
1772 :    
1773 :     =back
1774 :    
1775 :     =cut
1776 :    
1777 :     sub SplitKey {
1778 :     # Get the parameters.
1779 :     my ($self, $key) = @_;
1780 :     # Do the split.
1781 :     my ($realKey, $subKey) = split($self->{splitter}, $key, 2);
1782 :     # Insure the subkey has a value.
1783 :     if (! defined $subKey) {
1784 :     $subKey = '';
1785 :     }
1786 :     # Return the results.
1787 :     return ($realKey, $subKey);
1788 :     }
1789 :    
1790 : parrello 1.33
1791 : parrello 1.20 =head3 JoinKey
1792 :    
1793 : parrello 1.31 my $key = $ca->JoinKey($realKey, $subKey);
1794 : parrello 1.20
1795 :     Join a real key and a subkey together to make an external key. The external key is the attribute key
1796 :     used by the caller. The real key and the subkey are how the keys are represented in the database. The
1797 :     real key is the key to the B<AttributeKey> entity. The subkey is an attribute of the B<HasValueFor>
1798 :     relationship.
1799 :    
1800 :     =over 4
1801 :    
1802 :     =item realKey
1803 :    
1804 :     The real attribute key.
1805 :    
1806 :     =item subKey
1807 :    
1808 :     The subordinate portion of the attribute key.
1809 :    
1810 :     =item RETURN
1811 :    
1812 :     Returns a single string representing both keys.
1813 :    
1814 :     =back
1815 :    
1816 :     =cut
1817 :    
1818 :     sub JoinKey {
1819 :     # Get the parameters.
1820 :     my ($self, $realKey, $subKey) = @_;
1821 :     # Declare the return variable.
1822 :     my $retVal;
1823 :     # Check for a subkey.
1824 :     if ($subKey eq '') {
1825 :     # No subkey, so the real key is the key.
1826 :     $retVal = $realKey;
1827 :     } else {
1828 :     # Subkey found, so the two pieces must be joined by a splitter.
1829 :     $retVal = "$realKey$self->{splitter}$subKey";
1830 :     }
1831 :     # Return the result.
1832 :     return $retVal;
1833 :     }
1834 :    
1835 : parrello 1.26
1836 :     =head3 AttributeTable
1837 :    
1838 : parrello 1.31 my $tableHtml = CustomAttributes::AttributeTable($cgi, @attrList);
1839 : parrello 1.26
1840 :     Format the attribute data into an HTML table.
1841 :    
1842 :     =over 4
1843 :    
1844 :     =item cgi
1845 :    
1846 :     CGI query object used to generate the HTML
1847 :    
1848 :     =item attrList
1849 :    
1850 :     List of attribute results, in the format returned by the L</GetAttributes> or
1851 :     L</QueryAttributes> methods.
1852 :    
1853 :     =item RETURN
1854 :    
1855 :     Returns an HTML table displaying the attribute keys and values.
1856 :    
1857 :     =back
1858 :    
1859 :     =cut
1860 :    
1861 :     sub AttributeTable {
1862 :     # Get the parameters.
1863 :     my ($cgi, @attrList) = @_;
1864 :     # Accumulate the table rows.
1865 :     my @html = ();
1866 :     for my $attrData (@attrList) {
1867 :     # Format the object ID and key.
1868 :     my @columns = map { CGI::escapeHTML($_) } @{$attrData}[0,1];
1869 :     # Now we format the values. These remain unchanged unless one of them is a URL.
1870 :     my $lastValue = scalar(@{$attrData}) - 1;
1871 : parrello 1.40 push @columns, map { $_ =~ /^http:/ ? CGI::a({ href => $_ }, $_) : $_ } @{$attrData}[2 .. $lastValue];
1872 : parrello 1.26 # Assemble the values into a table row.
1873 : parrello 1.40 push @html, CGI::Tr(CGI::td(\@columns));
1874 : parrello 1.26 }
1875 :     # Format the table in the return variable.
1876 : parrello 1.40 my $retVal = CGI::table({ border => 2 }, CGI::Tr(CGI::th(['Object', 'Key', 'Values'])), @html);
1877 : parrello 1.26 # Return it.
1878 :     return $retVal;
1879 :     }
1880 : parrello 1.33
1881 :    
1882 :     =head2 Internal Utility Methods
1883 :    
1884 :     =head3 _KeyTable
1885 :    
1886 :     my $tableName = $ca->_KeyTable($keyName);
1887 :    
1888 :     Return the name of the table that contains the attribute values for the
1889 :     specified key.
1890 :    
1891 :     Most attribute values are stored in the default table (usually C<HasValueFor>).
1892 :     Some, however, are placed in private tables by themselves for performance reasons.
1893 :    
1894 :     =over 4
1895 :    
1896 :     =item keyName (optional)
1897 :    
1898 :     Name of the attribute key whose table name is desired. If not specified, the
1899 :     entire key/table hash is returned.
1900 :    
1901 :     =item RETURN
1902 :    
1903 :     Returns the name of the table containing the specified attribute key's values,
1904 :     or a reference to a hash that maps key names to table names.
1905 :    
1906 :     =back
1907 :    
1908 :     =cut
1909 :    
1910 :     sub _KeyTable {
1911 :     # Get the parameters.
1912 :     my ($self, $keyName) = @_;
1913 :     # Declare the return variable.
1914 :     my $retVal;
1915 :     # Insure the key table hash is present.
1916 :     if (! exists $self->{keyTables}) {
1917 : parrello 1.40 Trace("Creating key table.") if T(3);
1918 : parrello 1.33 $self->{keyTables} = { map { $_->[0] => $_->[1] } $self->GetAll(['AttributeKey'],
1919 :     "AttributeKey(relationship-name) <> ?",
1920 :     [$self->{defaultRel}],
1921 :     ['AttributeKey(id)', 'AttributeKey(relationship-name)']) };
1922 :     }
1923 :     # Get the key hash.
1924 :     my $keyHash = $self->{keyTables};
1925 :     # Does the user want a specific table or the whole thing?
1926 :     if ($keyName) {
1927 :     # Here we want a specific table. Is this key in the hash?
1928 :     if (exists $keyHash->{$keyName}) {
1929 :     # It's there, so return the specified table.
1930 :     $retVal = $keyHash->{$keyName};
1931 :     } else {
1932 :     # No, return the default table name.
1933 :     $retVal = $self->{defaultRel};
1934 :     }
1935 :     } else {
1936 :     # Here we want the whole hash.
1937 :     $retVal = $keyHash;
1938 :     }
1939 :     # Return the result.
1940 :     return $retVal;
1941 :     }
1942 :    
1943 :    
1944 :     =head3 _QueryResults
1945 :    
1946 :     my @attributeList = $attrDB->_QueryResults($query, $table, @values);
1947 :    
1948 :     Match the results of a query against value criteria and return
1949 :     the results. This is an internal method that splits the values coming back
1950 :     and matches the sections against the specified section patterns. It serves
1951 :     as the back end to L</GetAttributes> and L</FindAttributes>.
1952 :    
1953 :     =over 4
1954 :    
1955 :     =item query
1956 :    
1957 :     A query object that will return the desired records.
1958 :    
1959 :     =item table
1960 :    
1961 :     Name of the value table for the query.
1962 :    
1963 :     =item values
1964 :    
1965 :     List of the desired attribute values, section by section. If C<undef>
1966 :     or an empty string is specified, all values in that section will match. A
1967 :     generic match can be requested by placing a percent sign (C<%>) at the end.
1968 :     In that case, all values that match up to and not including the percent sign
1969 :     will match. You may also specify a regular expression enclosed
1970 :     in slashes. All values that match the regular expression will be returned. For
1971 :     performance reasons, only values have this extra capability.
1972 :    
1973 :     =item RETURN
1974 :    
1975 :     Returns a list of tuples. The first element in the tuple is an object ID, the
1976 :     second is an attribute key, and the remaining elements are the sections of
1977 :     the attribute value. All of the tuples will match the criteria set forth in
1978 :     the parameter list.
1979 :    
1980 :     =back
1981 :    
1982 :     =cut
1983 :    
1984 :     sub _QueryResults {
1985 :     # Get the parameters.
1986 :     my ($self, $query, $table, @values) = @_;
1987 :     # Declare the return value.
1988 :     my @retVal = ();
1989 : parrello 1.35 # We use this hash to check for duplicates.
1990 :     my %dupHash = ();
1991 : parrello 1.33 # Get the number of value sections we have to match.
1992 :     my $sectionCount = scalar(@values);
1993 :     # Loop through the assignments found.
1994 :     while (my $row = $query->Fetch()) {
1995 :     # Get the current row's data.
1996 :     my ($id, $realKey, $subKey, $valueString) = $row->Values(["$table(to-link)",
1997 :     "$table(from-link)",
1998 :     "$table(subkey)",
1999 :     "$table(value)"
2000 :     ]);
2001 :     # Form the key from the real key and the sub key.
2002 :     my $key = $self->JoinKey($realKey, $subKey);
2003 : parrello 1.38 # Break the value into sections.
2004 :     my @sections = split($self->{splitter}, $valueString);
2005 :     # Match each section against the incoming values. We'll assume we're
2006 :     # okay unless we learn otherwise.
2007 :     my $matching = 1;
2008 :     for (my $i = 0; $i < $sectionCount && $matching; $i++) {
2009 :     # We need to check to see if this section is generic.
2010 :     my $value = $values[$i];
2011 :     Trace("Current value pattern is \"$value\".") if T(4);
2012 :     if ($value =~ m#^/(.+)/[a-z]*$#) {
2013 :     Trace("Regular expression detected.") if T(4);
2014 :     # Here we have a regular expression match.
2015 :     my $section = $sections[$i];
2016 :     $matching = eval("\$section =~ $value");
2017 : parrello 1.39 } elsif (! defined $value) {
2018 :     # Wild card. Skip it.
2019 : parrello 1.38 } else {
2020 :     # Here we have a normal match.
2021 :     Trace("SQL match used.") if T(4);
2022 :     $matching = _CheckSQLPattern($values[$i], $sections[$i]);
2023 : parrello 1.35 }
2024 : parrello 1.38 }
2025 :     # If we match, consider writing this row to the return list.
2026 :     if ($matching) {
2027 :     # Check for a duplicate.
2028 :     my $wholeThing = join($self->{splitter}, $id, $key, $valueString);
2029 :     if (! $dupHash{$wholeThing}) {
2030 :     # It's okay, we're not a duplicate. Insure we don't duplicate this result.
2031 :     $dupHash{$wholeThing} = 1;
2032 : parrello 1.35 push @retVal, [$id, $key, @sections];
2033 : parrello 1.33 }
2034 :     }
2035 :     }
2036 :     # Return the rows found.
2037 :     return @retVal;
2038 :     }
2039 :    
2040 :    
2041 :     =head3 _LoadAttributeTable
2042 :    
2043 :     $attr->_LoadAttributeTable($tableName, $fileName, $stats, $mode);
2044 :    
2045 :     Load a file's data into an attribute table. This is an internal method
2046 :     provided for the convenience of L</LoadAttributesFrom>. It loads the
2047 :     specified file into the specified table and updates the statistics
2048 :     object.
2049 :    
2050 :     =over 4
2051 :    
2052 :     =item tableName
2053 :    
2054 :     Name of the table being loaded. This is usually C<HasValueFor>, but may
2055 :     be a different table for some specific attribute keys.
2056 :    
2057 :     =item fileName
2058 :    
2059 :     Name of the file containing a chunk of attribute data to load.
2060 :    
2061 :     =item stats
2062 :    
2063 :     Statistics object into which counts and times should be placed.
2064 :    
2065 :     =item mode
2066 :    
2067 :     Load mode for the file, usually C<low_priority>, C<concurrent>, or
2068 :     an empty string. The mode is used by some applications to control access
2069 :     to the table while it's being loaded. The default (empty string) is to lock the
2070 :     table until all the data's in place.
2071 :    
2072 :     =back
2073 :    
2074 :     =cut
2075 :    
2076 :     sub _LoadAttributeTable {
2077 :     # Get the parameters.
2078 :     my ($self, $tableName, $fileName, $stats, $mode) = @_;
2079 :     # Load the table from the file. Note that we don't do an analyze.
2080 :     # The analyze is done only after everything is complete.
2081 :     my $startTime = time();
2082 :     Trace("Loading attributes from $fileName: " . (-s $fileName) .
2083 :     " characters.") if T(3);
2084 :     my $loadStats = $self->LoadTable($fileName, $tableName,
2085 :     mode => $mode, partial => 1);
2086 :     # Record the load time.
2087 :     $stats->Add(insertTime => time() - $startTime);
2088 :     # Roll up the other statistics.
2089 :     $stats->Accumulate($loadStats);
2090 :     }
2091 :    
2092 :    
2093 :     =head3 _GetAllTables
2094 :    
2095 :     my @tables = $ca->_GetAllTables();
2096 :    
2097 :     Return a list of the names of all the tables used to store attribute
2098 :     values.
2099 :    
2100 :     =cut
2101 :    
2102 :     sub _GetAllTables {
2103 :     # Get the parameters.
2104 :     my ($self) = @_;
2105 :     # Start with the default table.
2106 :     my @retVal = $self->{defaultRel};
2107 :     # Add the tables named in the key hash. These tables are automatically
2108 :     # NOT the default, and each can only occur once, because alternate tables
2109 :     # are allocated on a per-key basis.
2110 :     my $keyHash = $self->_KeyTable();
2111 :     push @retVal, values %$keyHash;
2112 :     # Return the result.
2113 :     return @retVal;
2114 :     }
2115 :    
2116 :    
2117 :     =head3 _SplitKeyPattern
2118 :    
2119 :     my ($realKey, $subKey) = $ca->_SplitKeyPattern($keyChoice);
2120 :    
2121 :     Split a key pattern into the main part (the I<real key>) and a sub-part
2122 :     (the I<sub key>). This method differs from L</SplitKey> in that it treats
2123 :     the key as an SQL pattern instead of a raw string. Also, if there is no
2124 :     incoming sub-part, the sub-key will be undefined instead of an empty
2125 :     string.
2126 :    
2127 :     =over 4
2128 :    
2129 :     =item keyChoice
2130 :    
2131 :     SQL key pattern to be examined. This can either be a literal, an SQL pattern,
2132 :     a literal with an internal splitter code (usually C<::>) or an SQL pattern with
2133 :     an internal splitter. Note that the only SQL pattern we support is a percent
2134 :     sign (C<%>) at the end. This is the way we've declared things in the documentation,
2135 :     so users who try anything else will have problems.
2136 :    
2137 :     =item RETURN
2138 :    
2139 :     Returns a two-element list. The first element is the SQL pattern for the
2140 :     real key and the second is the SQL pattern for the sub-key. If the value
2141 :     for either one does not matter (e.g., the user wants a real key value of
2142 :     C<iedb> and doesn't care about the sub-key value), it will be undefined.
2143 :    
2144 :     =back
2145 :    
2146 :     =cut
2147 :    
2148 :     sub _SplitKeyPattern {
2149 :     # Get the parameters.
2150 :     my ($self, $keyChoice) = @_;
2151 :     # Declare the return variables.
2152 :     my ($realKey, $subKey);
2153 :     # Look for a splitter in the input.
2154 :     if ($keyChoice =~ /^(.*?)$self->{splitter}(.*)/) {
2155 :     # We found one. This means we can treat both sides of the
2156 :     # splitter as known patterns.
2157 :     ($realKey, $subKey) = ($1, $2);
2158 :     } elsif ($keyChoice =~ /%$/) {
2159 :     # Here we have a generic pattern for the whole key. The pattern
2160 :     # is treated as the correct pattern for the real key, but the
2161 :     # sub-key is considered to be wild.
2162 :     $realKey = $keyChoice;
2163 :     } else {
2164 :     # Here we have a literal pattern for the whole key. The pattern
2165 :     # is treated as the correct pattern for the real key, and the
2166 :     # sub-key is required to be blank.
2167 :     $realKey = $keyChoice;
2168 :     $subKey = '';
2169 :     }
2170 :     # Return the results.
2171 :     return ($realKey, $subKey);
2172 :     }
2173 :    
2174 :    
2175 :     =head3 _WherePart
2176 :    
2177 :     my ($sqlClause, $escapedValue) = _WherePart($tableName, $fieldName, $sqlPattern);
2178 :    
2179 :     Return the SQL clause and value for checking a field against the
2180 :     specified SQL pattern value. If the pattern is generic (ends in a C<%>),
2181 :     then a C<LIKE> expression is returned. Otherwise, an equality expression
2182 :     is returned. We take in information describing the field being checked,
2183 :     and the pattern we're checking against it. The output is a WHERE clause
2184 :     fragment for the comparison and a value to be used as a bound parameter
2185 :     value for the clause.
2186 :    
2187 :     =over 4
2188 :    
2189 :     =item tableName
2190 :    
2191 :     Name of the table containing the field we want checked by the clause.
2192 :    
2193 :     =item fieldName
2194 :    
2195 :     Name of the field to check in that table.
2196 :    
2197 :     =item sqlPattern
2198 :    
2199 :     Pattern to be compared against the field. If the last character is a percent sign
2200 :     (C<%>), it will be treated as a generic SQL pattern; otherwise, it will be treated
2201 :     as a literal.
2202 :    
2203 :     =item RETURN
2204 :    
2205 :     Returns a two-element list. The first element will be an SQL comparison expression
2206 :     and the second will be the value to be used as a bound parameter for the expression
2207 :     in order to
2208 :    
2209 :     =back
2210 :    
2211 :     =cut
2212 :    
2213 :     sub _WherePart {
2214 :     # Get the parameters.
2215 :     my ($tableName, $fieldName, $sqlPattern) = @_;
2216 :     # Declare the return variables.
2217 :     my ($sqlClause, $escapedValue);
2218 :     # Copy the pattern into the return area.
2219 :     $escapedValue = $sqlPattern;
2220 :     # Check the pattern. Is it generic or exact?
2221 : parrello 1.34 if ($sqlPattern =~ /(.+)%$/) {
2222 : parrello 1.33 # Yes, it is. We need a LIKE clause and we must escape the underscores
2223 : parrello 1.34 # and percents in the pattern (except for the last one, of course).
2224 :     $escapedValue = $1;
2225 : parrello 1.33 $escapedValue =~ s/(%|_)/\\$1/g;
2226 : parrello 1.34 $escapedValue .= "%";
2227 : parrello 1.33 $sqlClause = "$tableName($fieldName) LIKE ?";
2228 :     } else {
2229 :     # No, it isn't. We use an equality clause.
2230 :     $sqlClause = "$tableName($fieldName) = ?";
2231 :     }
2232 :     # Return the results.
2233 :     return ($sqlClause, $escapedValue);
2234 :     }
2235 :    
2236 :    
2237 :     =head3 _CheckSQLPattern
2238 :    
2239 :     my $flag = _CheckSQLPattern($pattern, $value);
2240 :    
2241 :     Return TRUE if the specified SQL pattern matches the specified value,
2242 :     else FALSE. The pattern is not a true full-blown SQL LIKE pattern: the
2243 :     only wild-carding allowed is a percent sign (C<%>) at the end.
2244 :    
2245 :     =over 4
2246 :    
2247 :     =item pattern
2248 :    
2249 :     SQL pattern to match against a value.
2250 :    
2251 :     =item value
2252 :    
2253 :     Value to match against an SQL pattern.
2254 :    
2255 :     =item RETURN
2256 :    
2257 :     Returns TRUE if the pattern matches the value, else FALSE.
2258 :    
2259 :     =back
2260 :    
2261 :     =cut
2262 :    
2263 :     sub _CheckSQLPattern {
2264 :     # Get the parameters.
2265 :     my ($pattern, $value) = @_;
2266 :     # Declare the return variable.
2267 :     my $retVal;
2268 :     # Check for a generic pattern.
2269 :     if ($pattern =~ /(.*)%$/) {
2270 :     # Here we have one. Do a substring match.
2271 :     $retVal = (substr($value, 0, length $1) eq $1);
2272 :     } else {
2273 :     # Here it's an exact match.
2274 :     $retVal = ($pattern eq $value);
2275 :     }
2276 : parrello 1.40 Trace("SQL pattern check: \"$value\" vs \"$pattern\" = $retVal.") if T(3);
2277 : parrello 1.33 # Return the result.
2278 :     return $retVal;
2279 :     }
2280 :    
2281 : parrello 1.36 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3