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

Annotation of /Sprout/CustomAttributes.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3