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

Annotation of /Sprout/CustomAttributes.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3