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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : parrello 1.1 package ERDB;
2 :    
3 :     use strict;
4 :     use Carp;
5 :     use Tracer;
6 :     use DBKernel;
7 :     use Data::Dumper;
8 :     use XML::Simple;
9 :     use DBQuery;
10 :     use DBObject;
11 :     use Stats;
12 :     use Time::HiRes qw(gettimeofday);
13 :    
14 :     =head1 Entity-Relationship Database Package
15 :    
16 :     =head2 Introduction
17 :    
18 :     The Entity-Relationship Database Package allows the client to create an easily-configurable
19 :     database of Entities connected by Relationships. Each entity is represented by one or more
20 :     relations in an underlying SQL database. Each relationship is represented by a single
21 :     relation that connects two entities.
22 :    
23 :     Although this package is designed for general use, all examples are derived from the
24 :     Sprout database, which is the first database implemented using this package.
25 :    
26 :     Each entity has at least one relation, the I<primary relation>, that has the same name as
27 :     the entity. The primary relation contains a field named C<id> that contains the unique
28 :     identifier of each entity instance. An entity may have additional relations that contain
29 :     fields which are optional or can occur more than once. For example, the B<FEATURE> entity
30 :     has a B<feature-type> attribute that occurs exactly once for each feature. This attribute
31 :     is implemented by a C<feature_type> column in the primary relation C<Feature>. In addition,
32 :     however, a feature may have zero or more aliases. These are implemented using a C<FeatureAlias>
33 :     relation that contains two fields-- the feature ID (C<id>) and the alias name (C<alias>).
34 :     The B<FEATURE> entity also contains an optional virulence number. This is implemented
35 :     as a separate relation C<FeatureVirulence> which contains an ID (C<id>) and a virulence number
36 :     (C<virulence>). If the virulence of a feature I<ABC> is known to be 6, there will be one row in the
37 :     C<FeatureVirulence> relation possessing the value I<ABC> as its ID and 6 as its virulence number.
38 :     If the virulence of I<ABC> is not known, there will not be any rows for it in C<FeatureVirulence>.
39 :    
40 :     Entities are connected by binary relationships implemented using single relations possessing the
41 :     same name as the relationship itself and that has an I<arity> of 1-to-1 (C<11>), 1-to-many (C<1M>),
42 :     or many-to-many (C<MM>). Each relationship's relation contains a C<from-link> field that contains the
43 :     ID of the source entity and a C<to-link> field that contains the ID of the target entity. The name
44 :     of the relationship is generally a verb phrase with the source entity as the subject and the
45 :     target entity as the object. So, for example, the B<ComesFrom> relationship connects the B<GENOME>
46 :     and B<SOURCE> entities, and indicates that a particular source organization participated in the
47 :     mapping of the genome. A source organization frequently participates in the mapping
48 :     of many genomes, and many source organizations can cooperate in the mapping of a single genome, so
49 :     this relationship has an arity of many-to-many (C<MM>). The relation that implements the B<ComesFrom>
50 :     relationship is called C<ComesFrom> and contains two fields-- C<from-link>, which contains a genome ID,
51 :     and C<to-link>, which contains a source ID.
52 :    
53 :     A relationship may itself have attributes. These attributes, known as I<intersection data attributes>,
54 :     are implemented as additional fields in the relationship's relation. So, for example, the
55 :     B<IsMadeUpOf> relationship connects the B<Contig> entity to the B<Sequence> entity, and is used
56 :     to determine which sequences make up a contig. The relationship has as an attribute the
57 :     B<start-position>, which indicates where in the contig that the sequence begins. This attribute
58 :     is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.
59 :    
60 :     The database itself is described by an XML file using the F<ERDatabase.xsd> schema. In addition to
61 :     all the data required to define the entities, relationships, and attributes, the schema provides
62 :     space for notes describing the data and what it means. These notes are used by L</ShowMetaData>
63 :     to generate documentation for the database.
64 :    
65 :     Finally, every entity and relationship object has a flag indicating if it is new or old. The object
66 :     is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it
67 :     was inserted by the L</InsertObject> method.
68 :    
69 :     To facilitate testing, the ERDB module supports automatic generation of test data. This process
70 :     is described in the L</GenerateEntity> and L</GenerateConnection> methods.
71 :    
72 :     =cut
73 :    
74 :     # GLOBALS
75 :    
76 :     # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.
77 :     # "maxLen" is the maximum permissible length of the incoming string data used to populate a field
78 :     # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation
79 :     #string is specified in the field definition.
80 :     my %TypeTable = ( char => { sqlType => 'CHAR(1)', maxLen => 1, dataGen => "StringGen('A')" },
81 :     int => { sqlType => 'INTEGER', maxLen => 20, dataGen => "IntGen(0, 99999999)" },
82 :     string => { sqlType => 'VARCHAR(255)', maxLen => 255, dataGen => "StringGen(IntGen(10,250))" },
83 :     text => { sqlType => 'TEXT', maxLen => 1000000000, dataGen => "StringGen(IntGen(80,1000))" },
84 :     date => { sqlType => 'BIGINT', maxLen => 80, dataGen => "DateGen(-7, 7, IntGen(0,1400))" },
85 :     float => { sqlType => 'DOUBLE PRECISION', maxLen => 40, dataGen => "FloatGen(0.0, 100.0)" },
86 :     boolean => { sqlType => 'SMALLINT', maxLen => 1, dataGen => "IntGen(0, 1)" },
87 :     'key-string' =>
88 :     { sqlType => 'VARCHAR(40)', maxLen => 40, dataGen => "StringGen(IntGen(10,40))" },
89 :     'name-string' =>
90 :     { sqlType => 'VARCHAR(80)', maxLen => 80, dataGen => "StringGen(IntGen(10,80))" },
91 :     'medium-string' =>
92 :     { sqlType => 'VARCHAR(160)', maxLen => 160, dataGen => "StringGen(IntGen(10,160))" },
93 :     );
94 :    
95 :     # Table translating arities into natural language.
96 :     my %ArityTable = ( '11' => 'one-to-one',
97 :     '1M' => 'one-to-many',
98 :     'MM' => 'many-to-many'
99 :     );
100 :    
101 :     # Table for interpreting string patterns.
102 :    
103 :     my %PictureTable = ( 'A' => "abcdefghijklmnopqrstuvwxyz",
104 :     '9' => "0123456789",
105 :     'X' => "abcdefghijklmnopqrstuvwxyz0123456789",
106 :     'V' => "aeiou",
107 :     'K' => "bcdfghjklmnoprstvwxyz"
108 :     );
109 :    
110 :     =head2 Public Methods
111 :    
112 :     =head3 new
113 :    
114 :     C<< my $database = ERDB::new($dbh, $metaFileName); >>
115 :    
116 :     Create a new ERDB object.
117 :    
118 :     =over 4
119 :    
120 :     =item dbh
121 :    
122 :     DBKernel database object for the target database.
123 :    
124 :     =item metaFileName
125 :    
126 :     Name of the XML file containing the metadata.
127 :    
128 :     =back
129 :    
130 :     =cut
131 :    
132 :     sub new {
133 :     # Get the parameters.
134 :     my ($class, $dbh, $metaFileName, $options) = @_;
135 :     # Load the meta-data.
136 :     my $metaData = _LoadMetaData($metaFileName);
137 :     # Create the object.
138 :     my $self = { _dbh => $dbh,
139 :     _metaData => $metaData,
140 :     _options => $options,
141 :     };
142 :     # Bless and return it.
143 :     bless $self;
144 :     return $self;
145 :     }
146 :    
147 :     =head3 ShowMetaData
148 :    
149 :     C<< $database->ShowMetaData($fileName); >>
150 :    
151 :     This method outputs a description of the database. This description can be used to help users create
152 :     the data to be loaded into the relations.
153 :    
154 :     =over 4
155 :    
156 :     =item filename
157 :    
158 :     The name of the output file.
159 :    
160 :     =back
161 :    
162 :     =cut
163 :    
164 :     sub ShowMetaData {
165 :     # Get the parameters.
166 :     my $self = shift @_;
167 :     my ($filename) = @_;
168 :     # Get the metadata and the title string.
169 :     my $metadata = $self->{_metaData};
170 :     # Get the title string.
171 :     my $title = $metadata->{Title};
172 :     # Get the entity and relationship lists.
173 :     my $entityList = $metadata->{Entities};
174 :     my $relationshipList = $metadata->{Relationships};
175 :     # Open the output file.
176 :     open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");
177 :     # Write the HTML heading stuff.
178 :     print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
179 :     print HTMLOUT "</head>\n<body>\n";
180 :     # Here we do the table of contents. It starts as an unordered list of section names. Each
181 :     # section contains an ordered list of entity or relationship subsections.
182 :     print HTMLOUT "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n";
183 :     # Loop through the Entities, displaying a list item for each.
184 :     foreach my $key (sort keys %{$entityList}) {
185 :     # Display this item.
186 :     print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n";
187 :     }
188 :     # Close off the entity section and start the relationship section.
189 :     print HTMLOUT "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n";
190 :     # Loop through the Relationships.
191 :     foreach my $key (sort keys %{$relationshipList}) {
192 :     # Display this item.
193 :     my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
194 :     print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
195 :     }
196 :     # Close off the relationship section and list the join table section.
197 :     print HTMLOUT "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n";
198 :     # Close off the table of contents itself.
199 :     print HTMLOUT "</ul>\n";
200 :     # Now we start with the actual data. Denote we're starting the entity section.
201 :     print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
202 :     # Loop through the entities.
203 :     for my $key (sort keys %{$entityList}) {
204 :     # Create the entity header. It contains a bookmark and the entity name.
205 :     print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";
206 :     # Get the entity data.
207 :     my $entityData = $entityList->{$key};
208 :     # If there's descriptive text, display it.
209 :     if (my $notes = $entityData->{Notes}) {
210 :     print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
211 :     }
212 :     # Now we want a list of the entity's relationships. First, we set up the relationship subsection.
213 :     print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
214 :     # Loop through the relationships.
215 :     for my $relationship (sort keys %{$relationshipList}) {
216 :     # Get the relationship data.
217 :     my $relationshipStructure = $relationshipList->{$relationship};
218 :     # Only use the relationship if if has this entity in its FROM or TO fields.
219 :     if ($relationshipStructure->{from} eq $key || $relationshipStructure->{to} eq $key) {
220 :     # Get the relationship sentence and append the arity.
221 :     my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
222 :     # Display the relationship data.
223 :     print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
224 :     }
225 :     }
226 :     # Close off the relationship list.
227 :     print HTMLOUT "</ul>\n";
228 :     # Get the entity's relations.
229 :     my $relationList = $entityData->{Relations};
230 :     # Create a header for the relation subsection.
231 :     print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n";
232 :     # Loop through the relations, displaying them.
233 :     for my $relation (sort keys %{$relationList}) {
234 :     my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
235 :     print HTMLOUT $htmlString;
236 :     }
237 :     }
238 :     # Denote we're starting the relationship section.
239 :     print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
240 :     # Loop through the relationships.
241 :     for my $key (sort keys %{$relationshipList}) {
242 :     # Get the relationship's structure.
243 :     my $relationshipStructure = $relationshipList->{$key};
244 :     # Create the relationship header.
245 :     my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
246 :     print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n";
247 :     # Get the entity names.
248 :     my $fromEntity = $relationshipStructure->{from};
249 :     my $toEntity = $relationshipStructure->{to};
250 :     # Describe the relationship arity. Note there's a bit of trickiness involving recursive
251 :     # many-to-many relationships. In a normal many-to-many we use two sentences to describe
252 :     # the arity (one for each direction). This is a bad idea for a recursive relationship,
253 :     # since both sentences will say the same thing.
254 :     my $arity = $relationshipStructure->{arity};
255 :     if ($arity eq "11") {
256 :     print HTMLOUT "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n";
257 :     } else {
258 :     print HTMLOUT "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n";
259 :     if ($arity eq "MM" && $fromEntity ne $toEntity) {
260 :     print HTMLOUT "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n";
261 :     }
262 :     }
263 :     print HTMLOUT "</p>\n";
264 :     # If there are notes on this relationship, display them.
265 :     if (my $notes = $relationshipStructure->{Notes}) {
266 :     print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
267 :     }
268 :     # Generate the relationship's relation table.
269 :     my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
270 :     print HTMLOUT $htmlString;
271 :     }
272 :     # Denote we're starting the join table.
273 :     print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
274 :     # Create a table header.
275 :     print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");
276 :     # Loop through the joins.
277 :     my $joinTable = $metadata->{Joins};
278 :     for my $joinKey (sort keys %{$joinTable}) {
279 :     # Separate out the source, the target, and the join clause.
280 :     $joinKey =~ m!([^/]*)/(.*)$!;
281 :     my ($source, $target, $clause) = ($self->ComputeObjectSentence($1),
282 :     $self->ComputeObjectSentence($2),
283 :     $joinTable->{$joinKey});
284 :     # Display them in a table row.
285 :     print HTMLOUT "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";
286 :     }
287 :     # Close the table.
288 :     print HTMLOUT _CloseTable();
289 :     # Close the document.
290 :     print HTMLOUT "</body>\n</html>\n";
291 :     # Close the file.
292 :     close HTMLOUT;
293 :     }
294 :    
295 :     =head3 DumpMetaData
296 :    
297 :     C<< $database->DumpMetaData(); >>
298 :    
299 :     Return a dump of the metadata structure.
300 :    
301 :     =cut
302 :    
303 :     sub DumpMetaData {
304 :     # Get the parameters.
305 :     my $self = shift @_;
306 :     # Dump the meta-data.
307 :     return Data::Dumper::Dumper($self->{_metaData});
308 :     }
309 :    
310 :     =head3 CreateTables
311 :    
312 :     C<< $datanase->CreateTables(); >>
313 :    
314 :     This method creates the tables for the database from the metadata structure loaded by the
315 :     constructor. It is expected this function will only be used on rare occasions, when the
316 :     user needs to start with an empty database. Otherwise, the L</LoadTables> method can be
317 :     used by itself with the truncate flag turned on.
318 :    
319 :     =cut
320 :    
321 :     sub CreateTables {
322 :     # Get the parameters.
323 :     my $self = shift @_;
324 :     my $metadata = $self->{_metaData};
325 :     my $dbh = $self->{_dbh};
326 :     # Loop through the entities.
327 :     while (my ($entityName, $entityData) = each %{$metadata->{Entities}}) {
328 :     # Tell the user what we're doing.
329 :     Trace("Creating relations for entity $entityName.") if T(1);
330 :     # Loop through the entity's relations.
331 :     for my $relationName (keys %{$entityData->{Relations}}) {
332 :     # Create a table for this relation.
333 :     $self->CreateTable($relationName);
334 :     Trace("Relation $relationName created.") if T(1);
335 :     }
336 :     }
337 :     # Loop through the relationships.
338 :     my $relationshipTable = $metadata->{Relationships};
339 :     for my $relationshipName (keys %{$metadata->{Relationships}}) {
340 :     # Create a table for this relationship.
341 :     Trace("Creating relationship $relationshipName.") if T(1);
342 :     $self->CreateTable($relationshipName);
343 :     }
344 :     }
345 :    
346 :     =head3 CreateTable
347 :    
348 :     C<< $database->CreateTable($tableName, $indexFlag); >>
349 :    
350 :     Create the table for a relation and optionally create its indexes.
351 :    
352 :     =over 4
353 :    
354 :     =item relationName
355 :    
356 :     Name of the relation (which will also be the table name).
357 :    
358 :     =item $indexFlag
359 :    
360 :     TRUE if the indexes for the relation should be created, else FALSE. If FALSE,
361 :     L</CreateIndexes> must be called later to bring the indexes into existence.
362 :    
363 :     =back
364 :    
365 :     =cut
366 :    
367 :     sub CreateTable {
368 :     # Get the parameters.
369 :     my $self = shift @_;
370 :     my ($relationName, $indexFlag) = @_;
371 :     # Get the database handle.
372 :     my $dbh = $self->{_dbh};
373 :     # Get the relation data and determine whether or not the relation is primary.
374 :     my $relationData = $self->_FindRelation($relationName);
375 :     my $rootFlag = $self->_IsPrimary($relationName);
376 :     # Create a list of the field data.
377 :     my @fieldList;
378 :     for my $fieldData (@{$relationData->{Fields}}) {
379 :     # Assemble the field name and type.
380 :     my $fieldName = _FixName($fieldData->{name});
381 :     my $fieldString = "$fieldName $TypeTable{$fieldData->{type}}->{sqlType} NOT NULL ";
382 :     # Push the result into the field list.
383 :     push @fieldList, $fieldString;
384 :     }
385 :     # If this is a root table, add the "new_record" flag. It defaults to 0, so
386 :     if ($rootFlag) {
387 :     push @fieldList, "new_record $TypeTable{boolean}->{sqlType} NOT NULL DEFAULT 0";
388 :     }
389 :     # Convert the field list into a comma-delimited string.
390 :     my $fieldThing = join(', ', @fieldList);
391 :     # Insure the table is not already there.
392 :     $dbh->drop_table(tbl => $relationName);
393 :     Trace("Table $relationName dropped.") if T(2);
394 :     # Create the table.
395 :     Trace("Creating table $relationName: $fieldThing") if T(2);
396 :     $dbh->create_table(tbl => $relationName, flds => $fieldThing);
397 :     Trace("Relation $relationName created in database.") if T(2);
398 :     # If we want to build the indexes, we do it here.
399 :     if ($indexFlag) {
400 :     $self->CreateIndex($relationName);
401 :     }
402 :     }
403 :    
404 :     =head3 CreateIndex
405 :    
406 :     C<< $database->CreateIndex($relationName); >>
407 :    
408 :     Create the indexes for a relation. If a table is being loaded from a large source file (as
409 :     is the case in L</LoadTable>), it is best to create the indexes after the load. If that is
410 :     the case, then L</CreateTable> should be called with the index flag set to FALSE, and this
411 :     method used after the load to create the indexes for the table.
412 :    
413 :     =cut
414 :    
415 :     sub CreateIndex {
416 :     # Get the parameters.
417 :     my $self = shift @_;
418 :     my ($relationName) = @_;
419 :     # Get the relation's descriptor.
420 :     my $relationData = $self->_FindRelation($relationName);
421 :     # Get the database handle.
422 :     my $dbh = $self->{_dbh};
423 :     # Now we need to create this relation's indexes. We do this by looping through its index table.
424 :     while (my ($indexName, $indexData) = each %{$relationData->{Indexes}}) {
425 :     # Get the index's field list.
426 :     my @fieldList = _FixNames(@{$indexData->{IndexFields}});
427 :     my $flds = join(', ', @fieldList);
428 :     # Get the index's uniqueness flag.
429 :     my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');
430 :     # Create the index.
431 :     $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);
432 :     Trace("Index created: $indexName for $relationName ($flds)") if T(1);
433 :     }
434 :     }
435 :    
436 :     =head3 LoadTables
437 :    
438 :     C<< my $stats = $database->LoadTables($directoryName, $rebuild); >>
439 :    
440 :     This method will load the database tables from a directory. The tables must already have been created
441 :     in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
442 :     all of the relations to be loaded must have a file in the directory with the same name as the relation
443 :     (optionally with a suffix of C<.dtx>). Each file must be a tab-delimited table of field values. Each
444 :     line of the file will be loaded as a row of the target relation table. The field values should be in
445 :     the same order as the fields in the relation tables generated by L</ShowMetaData>. The old data is
446 :     erased before the new data is loaded in.
447 :    
448 :     A certain amount of translation automatically takes place. Ctrl-M characters are deleted, and
449 :     tab and new-line characters inside a field are escaped as C<\t> and C<\n>, respectively. Dates must
450 :     be entered as a Unix timestamp, that is, as an integer number of seconds since the base epoch.
451 :    
452 :     =over 4
453 :    
454 :     =item directoryName
455 :    
456 :     Name of the directory containing the relation files to be loaded.
457 :    
458 :     =item rebuild
459 :    
460 :     TRUE if the tables should be dropped and rebuilt, else FALSE. This is, unfortunately, the
461 :     only way to erase existing data in the tables, since the TRUNCATE command is not supported
462 :     by all of the DB engines we use.
463 :    
464 :     =item RETURN
465 :    
466 :     Returns a statistical object describing the number of records read and a list of the error messages.
467 :    
468 :     =back
469 :    
470 :     =cut
471 :    
472 :     sub LoadTables {
473 :     # Get the parameters.
474 :     my $self = shift @_;
475 :     my ($directoryName, $rebuild) = @_;
476 :     # Start the timer.
477 :     my $startTime = gettimeofday;
478 :     # Clean any trailing slash from the directory name.
479 :     $directoryName =~ s!/\\$!!;
480 :     # Declare the return variable.
481 :     my $retVal = Stats->new();
482 :     # Get the metadata structure.
483 :     my $metaData = $self->{_metaData};
484 :     # Loop through the entities.
485 :     for my $entity (values %{$metaData->{Entities}}) {
486 :     # Loop through the entity's relations.
487 :     for my $relationName (keys %{$entity->{Relations}}) {
488 :     # Try to load this relation.
489 :     my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
490 :     # Accumulate the statistics.
491 :     $retVal->Accumulate($result);
492 :     }
493 :     }
494 :     # Loop through the relationships.
495 :     for my $relationshipName (keys %{$metaData->{Relationships}}) {
496 :     # Try to load this relationship's relation.
497 :     my $result = $self->_LoadRelation($directoryName, $relationshipName, $rebuild);
498 :     # Accumulate the statistics.
499 :     $retVal->Accumulate($result);
500 :     }
501 :     # Add the duration of the load to the statistical object.
502 :     $retVal->Add('duration', gettimeofday - $startTime);
503 :     # Return the accumulated statistics.
504 :     return $retVal;
505 :     }
506 :    
507 :     =head3 GetTableNames
508 :    
509 :     C<< my @names = $database->GetTableNames; >>
510 :    
511 :     Return a list of the relations required to implement this database.
512 :    
513 :     =cut
514 :    
515 :     sub GetTableNames {
516 :     # Get the parameters.
517 :     my $self = shift @_;
518 :     # Get the relation list from the metadata.
519 :     my $relationTable = $self->{_metaData}->{RelationTable};
520 :     # Return the relation names.
521 :     return keys %{$relationTable};
522 :     }
523 :    
524 :     =head3 GetEntityTypes
525 :    
526 :     C<< my @names = $database->GetEntityTypes; >>
527 :    
528 :     Return a list of the entity type names.
529 :    
530 :     =cut
531 :    
532 :     sub GetEntityTypes {
533 :     # Get the database object.
534 :     my $self = shift @_;
535 :     # Get the entity list from the metadata object.
536 :     my $entityList = $self->{_metaData}->{Entities};
537 :     # Return the list of entity names in alphabetical order.
538 :     return sort keys %{$entityList};
539 :     }
540 :    
541 :     =head3 Get
542 :    
543 :     C<< my $query = $database->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>
544 :    
545 :     This method returns a query object for entities of a specified type using a specified filter.
546 :     The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
547 :     field name represented in the form B<I<objectName>(I<fieldName>)>. For example, the
548 :     following call requests all B<Genome> objects for the genus specified in the variable
549 :     $genus.
550 :    
551 :     C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", $genus); >>
552 :    
553 :     The WHERE clause contains a single question mark, so there is a single additional
554 :     parameter representing the parameter value. It would also be possible to code
555 :    
556 :     C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>
557 :    
558 :     however, this version of the call would generate a syntax error if there were any quote
559 :     characters inside the variable C<$genus>.
560 :    
561 :     The use of the strange parenthesized notation for field names enables us to distinguish
562 :     hyphens contained within field names from minus signs that participate in the computation
563 :     of the WHERE clause. All of the methods that manipulate fields will use this same notation.
564 :    
565 :     It is possible to specify multiple entity and relationship names in order to retrieve more than
566 :     one object's data at the same time, which allows highly complex joined queries. For example,
567 :    
568 :     C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>
569 :    
570 :     If multiple names are specified, then the query processor will automatically determine a
571 :     join path between the entities and relationships. The algorithm used is very simplistic.
572 :     In particular, you can't specify any entity or relationship more than once, and if a
573 :     relationship is recursive, the path is determined by the order in which the entity
574 :     and the relationship appear. For example, consider a recursive relationship B<IsParentOf>
575 :     which relates B<People> objects to other B<People> objects. If the join path is
576 :     coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,
577 :     the join path is C<['IsParentOf', 'People']>, then the people returned will be children.
578 :    
579 :     =over 4
580 :    
581 :     =item objectNames
582 :    
583 :     List containing the names of the entity and relationship objects to be retrieved.
584 :    
585 :     =item filterClause
586 :    
587 :     WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
588 :     be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
589 :     specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
590 :     in the filter clause should be added to the parameter list as additional parameters. The
591 :     fields in a filter clause can come from primary entity relations, relationship relations,
592 :     or secondary entity relations; however, all of the entities and relationships involved must
593 :     be included in the list of object names.
594 :    
595 :     The filter clause can also specify a sort order. To do this, simply follow the filter string
596 :     with an ORDER BY clause. For example, the following filter string gets all genomes for a
597 :     particular genus and sorts them by species name.
598 :    
599 :     C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
600 :    
601 :     The rules for field references in a sort order are the same as those for field references in the
602 :     filter clause in general; however, odd things may happen if a sort field is from a secondary
603 :     relation.
604 :    
605 :     =item param1, param2, ..., paramN
606 :    
607 :     Parameter values to be substituted into the filter clause.
608 :    
609 :     =item RETURN
610 :    
611 :     Returns a B<DBQuery> that can be used to iterate through all of the results.
612 :    
613 :     =back
614 :    
615 :     =cut
616 :    
617 :     sub Get {
618 :     # Get the parameters.
619 :     my $self = shift @_;
620 :     my ($objectNames, $filterClause, @params) = @_;
621 :     # Construct the SELECT statement. The general pattern is
622 :     #
623 :     # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN
624 :     #
625 :     my $dbh = $self->{_dbh};
626 :     my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .
627 :     join(', ', @{$objectNames});
628 :     # Check for a filter clause.
629 :     if ($filterClause) {
630 :     # Here we have one, so we convert its field names and add it to the query. First,
631 :     # We create a copy of the filter string we can work with.
632 :     my $filterString = $filterClause;
633 :     # Next, we sort the object names by length. This helps protect us from finding
634 :     # object names inside other object names when we're doing our search and replace.
635 :     my @sortedNames = sort { length($b) - length($a) } @{$objectNames};
636 :     # We will also keep a list of conditions to add to the WHERE clause in order to link
637 :     # entities and relationships as well as primary relations to secondary ones.
638 :     my @joinWhere = ();
639 :     # The final preparatory step is to create a hash table of relation names. The
640 :     # table begins with the relation names already in the SELECT command.
641 :     my %fromNames = ();
642 :     for my $objectName (@sortedNames) {
643 :     $fromNames{$objectName} = 1;
644 :     }
645 :     # We are ready to begin. We loop through the object names, replacing each
646 :     # object name's field references by the corresponding SQL field reference.
647 :     # Along the way, if we find a secondary relation, we will need to add it
648 :     # to the FROM clause.
649 :     for my $objectName (@sortedNames) {
650 :     # Get the length of the object name plus 2. This is the value we add to the
651 :     # size of the field name to determine the size of the field reference as a
652 :     # whole.
653 :     my $nameLength = 2 + length $objectName;
654 :     # Get the object's field list.
655 :     my $fieldList = $self->_GetFieldTable($objectName);
656 :     # Find the field references for this object.
657 :     while ($filterString =~ m/$objectName\(([^)]*)\)/g) {
658 :     # At this point, $1 contains the field name, and the current position
659 :     # is set immediately after the final parenthesis. We pull out the name of
660 :     # the field and the position and length of the field reference as a whole.
661 :     my $fieldName = $1;
662 :     my $len = $nameLength + length $fieldName;
663 :     my $pos = pos($filterString) - $len;
664 :     # Insure the field exists.
665 :     if (!exists $fieldList->{$fieldName}) {
666 :     Confess("Field $fieldName not found for object $objectName.");
667 :     } else {
668 :     # Get the field's relation.
669 :     my $relationName = $fieldList->{$fieldName}->{relation};
670 :     # Insure the relation is in the FROM clause.
671 :     if (!exists $fromNames{$relationName}) {
672 :     # Add the relation to the FROM clause.
673 :     $command .= ", $relationName";
674 :     # Create its join sub-clause.
675 :     push @joinWhere, "$objectName.id = $relationName.id";
676 :     # Denote we have it available for future fields.
677 :     $fromNames{$relationName} = 1;
678 :     }
679 :     # Form an SQL field reference from the relation name and the field name.
680 :     my $sqlReference = "$relationName." . _FixName($fieldName);
681 :     # Put it into the filter string in place of the old value.
682 :     substr($filterString, $pos, $len) = $sqlReference;
683 :     # Reposition the search.
684 :     pos $filterString = $pos + length $sqlReference;
685 :     }
686 :     }
687 :     }
688 :     # The next step is to join the objects together. We only need to do this if there
689 :     # is more than one object in the object list. We start with the first object and
690 :     # run through the objects after it. Note also that we make a safety copy of the
691 :     # list before running through it.
692 :     my @objectList = @{$objectNames};
693 :     my $lastObject = shift @objectList;
694 :     # Get the join table.
695 :     my $joinTable = $self->{_metaData}->{Joins};
696 :     # Loop through the object list.
697 :     for my $thisObject (@objectList) {
698 :     # Look for a join.
699 :     my $joinKey = "$lastObject/$thisObject";
700 :     if (!exists $joinTable->{$joinKey}) {
701 :     # Here there's no join, so we throw an error.
702 :     Confess("No join exists to connect from $lastObject to $thisObject.");
703 :     } else {
704 :     # Get the join clause and add it to the WHERE list.
705 :     push @joinWhere, $joinTable->{$joinKey};
706 :     # Save this object as the last object for the next iteration.
707 :     $lastObject = $thisObject;
708 :     }
709 :     }
710 :     # Now we need to handle the whole ORDER BY thing. We'll put the order by clause
711 :     # in the following variable.
712 :     my $orderClause = "";
713 :     # Locate the ORDER BY verb (if any).
714 :     if ($filterString =~ m/^(.*)ORDER BY/g) {
715 :     # Here we have an ORDER BY verb. Split it off of the filter string.
716 :     my $pos = pos $filterString;
717 :     $orderClause = substr($filterString, $pos);
718 :     $filterString = $1;
719 :     }
720 :     # Add the filter and the join clauses (if any) to the SELECT command.
721 :     if ($filterString) {
722 :     push @joinWhere, "($filterString)";
723 :     }
724 :     if (@joinWhere) {
725 :     $command .= " WHERE " . join(' AND ', @joinWhere);
726 :     }
727 :     # Add the sort clause (if any) to the SELECT command.
728 :     if ($orderClause) {
729 :     $command .= " ORDER BY $orderClause";
730 :     }
731 :     }
732 :     Trace("SQL query: $command") if T(2);
733 :     Trace("PARMS: '" . (join "', '", @params) . "'") if (T(3) && (@params > 0));
734 :     my $sth = $dbh->prepare_command($command);
735 :     # Execute it with the parameters bound in.
736 :     $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());
737 :     # Return the statement object.
738 :     my $retVal = DBQuery::_new($self, $sth, @{$objectNames});
739 :     return $retVal;
740 :     }
741 :    
742 :     =head3 ComputeObjectSentence
743 :    
744 :     C<< my $sentence = $database->ComputeObjectSentence($objectName); >>
745 :    
746 :     Check an object name, and if it is a relationship convert it to a relationship sentence.
747 :    
748 :     =over 4
749 :    
750 :     =item objectName
751 :    
752 :     Name of the entity or relationship.
753 :    
754 :     =item RETURN
755 :    
756 :     Returns a string containing the entity name or a relationship sentence.
757 :    
758 :     =back
759 :    
760 :     =cut
761 :    
762 :     sub ComputeObjectSentence {
763 :     # Get the parameters.
764 :     my $self = shift @_;
765 :     my ($objectName) = @_;
766 :     # Set the default return value.
767 :     my $retVal = $objectName;
768 :     # Look for the object as a relationship.
769 :     my $relTable = $self->{_metaData}->{Relationships};
770 :     if (exists $relTable->{$objectName}) {
771 :     # Get the relationship sentence.
772 :     $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});
773 :     }
774 :     # Return the result.
775 :     return $retVal;
776 :     }
777 :    
778 :     =head3 DumpRelations
779 :    
780 :     C<< $database->DumpRelations($outputDirectory); >>
781 :    
782 :     Write the contents of all the relations to tab-delimited files in the specified directory.
783 :     Each file will have the same name as the relation dumped, with an extension of DTX.
784 :    
785 :     =over 4
786 :    
787 :     =item outputDirectory
788 :    
789 :     Name of the directory into which the relation files should be dumped.
790 :    
791 :     =back
792 :    
793 :     =cut
794 :    
795 :     sub DumpRelations {
796 :     # Get the parameters.
797 :     my $self = shift @_;
798 :     my ($outputDirectory) = @_;
799 :     # Now we need to run through all the relations. First, we loop through the entities.
800 :     my $metaData = $self->{_metaData};
801 :     my $entities = $metaData->{Entities};
802 :     while (my ($entityName, $entityStructure) = each %{$entities}) {
803 :     # Get the entity's relations.
804 :     my $relationList = $entityStructure->{Relations};
805 :     # Loop through the relations, dumping them.
806 :     while (my ($relationName, $relation) = each %{$relationList}) {
807 :     $self->_DumpRelation($outputDirectory, $relationName, $relation);
808 :     }
809 :     }
810 :     # Next, we loop through the relationships.
811 :     my $relationships = $metaData->{Relationships};
812 :     while (my ($relationshipName, $relationshipStructure) = each %{$relationships}) {
813 :     # Dump this relationship's relation.
814 :     $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
815 :     }
816 :     }
817 :    
818 :     =head3 InsertObject
819 :    
820 :     C<< my $ok = $database->InsertObject($objectType, \%fieldHash); >>
821 :    
822 :     Insert an object into the database. The object is defined by a type name and then a hash
823 :     of field names to values. Field values in the primary relation are represented by scalars.
824 :     (Note that for relationships, the primary relation is the B<only> relation.)
825 :     Field values for the other relations comprising the entity are always list references. For
826 :     example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
827 :     C<ZP_00210270.1> and C<gi|46206278>.
828 :    
829 :     C<< $database->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>
830 :    
831 :     The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
832 :     property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
833 :    
834 :     C<< $database->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>
835 :    
836 :     =over 4
837 :    
838 :     =item newObjectType
839 :    
840 :     Type name of the object to insert.
841 :    
842 :     =item fieldHash
843 :    
844 :     Hash of field names to values.
845 :    
846 :     =item RETURN
847 :    
848 :     Returns 1 if successful, 0 if an error occurred.
849 :    
850 :     =back
851 :    
852 :     =cut
853 :    
854 :     sub InsertObject {
855 :     # Get the parameters.
856 :     my $self = shift @_;
857 :     my ($newObjectType, $fieldHash) = @_;
858 :     # Denote that so far we appear successful.
859 :     my $retVal = 1;
860 :     # Get the database handle.
861 :     my $dbh = $self->{_dbh};
862 :     # Get the relation list.
863 :     my $relationTable = $self->_GetRelationTable($newObjectType);
864 :     # Loop through the relations. We'll build insert statements for each one. If a relation is
865 :     # secondary, we may end up generating multiple insert statements. If an error occurs, we
866 :     # stop the loop.
867 :     while ($retVal && (my ($relationName, $relationDefinition) = each %{$relationTable})) {
868 :     # Get the relation's fields. For each field we will collect a value in the corresponding
869 :     # position of the @valueList array. If one of the fields is missing, we will add it to the
870 :     # @missing list.
871 :     my @fieldList = @{$relationDefinition->{Fields}};
872 :     my @fieldNameList = ();
873 :     my @valueList = ();
874 :     my @missing = ();
875 :     my $recordCount = 1;
876 :     for my $fieldDescriptor (@fieldList) {
877 :     # Get the field name and save it. Note we need to fix it up so the hyphens
878 :     # are converted to underscores.
879 :     my $fieldName = $fieldDescriptor->{name};
880 :     push @fieldNameList, _FixName($fieldName);
881 :     # Look for the named field in the incoming structure. Note that we are looking
882 :     # for the real field name, not the fixed-up one!
883 :     if (exists $fieldHash->{$fieldName}) {
884 :     # Here we found the field. Stash it in the value list.
885 :     my $value = $fieldHash->{$fieldName};
886 :     push @valueList, $value;
887 :     # If the value is a list, we may need to increment the record count.
888 :     if (ref $value eq "ARRAY") {
889 :     my $thisCount = @{$value};
890 :     if ($recordCount == 1) {
891 :     # Here we have our first list, so we save its count.
892 :     $recordCount = $thisCount;
893 :     } elsif ($recordCount != $thisCount) {
894 :     # Here we have a second list, so its length has to match the
895 :     # previous lists.
896 :     Trace("Field $value in new $newObjectType object has an invalid list length $thisCount. Expected $recordCount.") if T(0);
897 :     $retVal = 0;
898 :     }
899 :     }
900 :     } else {
901 :     # Here the field is not present. Flag it as missing.
902 :     push @missing, $fieldName;
903 :     }
904 :     }
905 :     # If we are the primary relation, add the new-record flag.
906 :     if ($relationName eq $newObjectType) {
907 :     push @valueList, 1;
908 :     push @fieldNameList, "new_record";
909 :     }
910 :     # Only proceed if there are no missing fields.
911 :     if (@missing > 0) {
912 :     Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
913 :     join(' ', @missing)) if T(1);
914 :     } else {
915 :     # Build the INSERT statement.
916 :     my $statement = "INSERT INTO $relationName (" . join (', ', @fieldNameList) .
917 :     ") VALUES (";
918 :     # Create a marker list of the proper size and put it in the statement.
919 :     my @markers = ();
920 :     while (@markers < @fieldNameList) { push @markers, '?'; }
921 :     $statement .= join(', ', @markers) . ")";
922 :     # We have the insert statement, so prepare it.
923 :     my $sth = $dbh->prepare_command($statement);
924 :     Trace("Insert statement prepared: $statement") if T(3);
925 :     # Now we loop through the values. If a value is scalar, we use it unmodified. If it's
926 :     # a list, we use the current element. The values are stored in the @parameterList array.
927 :     my $done = 0;
928 :     for (my $i = 0; $i < $recordCount; $i++) {
929 :     # Clear the parameter list array.
930 :     my @parameterList = ();
931 :     # Loop through the values.
932 :     for my $value (@valueList) {
933 :     # Check to see if this is a scalar value.
934 :     if (ref $value eq "ARRAY") {
935 :     # Here we have a list value. Pull the current entry.
936 :     push @parameterList, $value->[$i];
937 :     } else {
938 :     # Here we have a scalar value. Use it unmodified.
939 :     push @parameterList, $value;
940 :     }
941 :     }
942 :     # Execute the INSERT statement with the specified parameter list.
943 :     $retVal = $sth->execute(@parameterList);
944 :     if (!$retVal) {
945 :     my $errorString = $sth->errstr();
946 :     Trace("Insert error: $errorString.") if T(0);
947 :     }
948 :     }
949 :     }
950 :     }
951 :     # Return the success indicator.
952 :     return $retVal;
953 :     }
954 :    
955 :     =head3 LoadTable
956 :    
957 :     C<< my %results = $database->LoadTable($fileName, $relationName, $truncateFlag); >>
958 :    
959 :     Load data from a tab-delimited file into a specified table, optionally re-creating the table first.
960 :    
961 :     =over 4
962 :    
963 :     =item fileName
964 :    
965 :     Name of the file from which the table data should be loaded.
966 :    
967 :     =item relationName
968 :    
969 :     Name of the relation to be loaded. This is the same as the table name.
970 :    
971 :     =item truncateFlag
972 :    
973 :     TRUE if the table should be dropped and re-created, else FALSE
974 :    
975 :     =item RETURN
976 :    
977 :     Returns a statistical object containing the number of records read and a list of the error messages.
978 :    
979 :     =back
980 :    
981 :     =cut
982 :     sub LoadTable {
983 :     # Get the parameters.
984 :     my $self = shift @_;
985 :     my ($fileName, $relationName, $truncateFlag) = @_;
986 :     # Create the statistical return object.
987 :     my $retVal = _GetLoadStats();
988 :     # Trace the fact of the load.
989 :     Trace("Loading table $relationName from $fileName") if T(1);
990 :     # Get the database handle.
991 :     my $dbh = $self->{_dbh};
992 :     # Get the relation data.
993 :     my $relation = $self->_FindRelation($relationName);
994 :     # Check the truncation flag.
995 :     if ($truncateFlag) {
996 :     Trace("Creating table $relationName") if T(1);
997 :     # Re-create the table without its index.
998 :     $self->CreateTable($relationName, 0);
999 :     }
1000 :     # Determine whether or not this is a primary relation. Primary relations have an extra
1001 :     # field indicating whether or not a given object is new or was loaded from the flat files.
1002 :     my $primary = $self->_IsPrimary($relationName);
1003 :     # Get the number of fields in this relation.
1004 :     my @fieldList = @{$relation->{Fields}};
1005 :     my $fieldCount = @fieldList;
1006 :     # Record the number of expected fields.
1007 :     my $expectedFields = $fieldCount + ($primary ? 1 : 0);
1008 :     # Start a database transaction.
1009 :     $dbh->begin_tran;
1010 :     # Open the relation file. We need to create a cleaned-up copy before loading.
1011 :     open TABLEIN, '<', $fileName;
1012 :     my $tempName = "$fileName.tbl";
1013 :     open TABLEOUT, '>', $tempName;
1014 :     # Loop through the file.
1015 :     while (<TABLEIN>) {
1016 :     # Chop off the new-line character.
1017 :     my $record = $_;
1018 :     chomp $record;
1019 :     # Escape all the backslashes found in the line.
1020 :     $record =~ s/\\/\\\\/g;
1021 :     # If this is a primary relation, add a 0 for the new-record flag (indicating that
1022 :     # this record is not new, but part of the original load).
1023 :     if ($primary) {
1024 :     $record .= "\t0";
1025 :     }
1026 :     # Write the record.
1027 :     print TABLEOUT "$record\n";
1028 :     # Count the record read.
1029 :     my $count = $retVal->Add('records');
1030 :     }
1031 :     # Close the files.
1032 :     close TABLEIN;
1033 :     close TABLEOUT;
1034 :     # Load the table.
1035 :     my $rv;
1036 :     eval {
1037 :     $rv = $dbh->load_table(file => $tempName, tbl => $relationName);
1038 :     };
1039 :     if (!defined $rv) {
1040 :     $retVal->AddMessage("Table load failed for $relationName.");
1041 :     Trace("Table load failed for $relationName.") if T(1);
1042 :     } else {
1043 :     # Here we successfully loaded the table. Trace the number of records loaded.
1044 :     Trace("$retVal->{records} records read for $relationName.") if T(1);
1045 :     # If we're rebuilding, we need to create the table indexes.
1046 :     if ($truncateFlag) {
1047 :     eval {
1048 :     $self->CreateIndex($relationName);
1049 :     };
1050 :     if ($@) {
1051 :     $retVal->AddMessage($@);
1052 :     }
1053 :     }
1054 :     }
1055 :     # Commit the database changes.
1056 :     $dbh->commit_tran;
1057 :     # Delete the temporary file.
1058 :     unlink $tempName;
1059 :     # Return the statistics.
1060 :     return $retVal;
1061 :     }
1062 :    
1063 :     =head3 GenerateEntity
1064 :    
1065 :     C<< my $fieldHash = $database->GenerateEntity($id, $type, \%values); >>
1066 :    
1067 :     Generate the data for a new entity instance. This method creates a field hash suitable for
1068 :     passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest
1069 :     of the fields are generated using information in the database schema.
1070 :    
1071 :     Each data type has a default algorithm for generating random test data. This can be overridden
1072 :     by including a B<DataGen> element in the field. If this happens, the content of the element is
1073 :     executed as a PERL program in the context of this module. The element may make use of a C<$this>
1074 :     variable which contains the field hash as it has been built up to the current point. If any
1075 :     fields are dependent on other fields, the C<pass> attribute can be used to control the order
1076 :     in which the fields are generated. A field with a high data pass number will be generated after
1077 :     a field with a lower one. If any external values are needed, they should be passed in via the
1078 :     optional third parameter, which will be available to the data generation script under the name
1079 :     C<$value>. Several useful utility methods are provided for generating random values, including
1080 :     L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated
1081 :     in the form of a timestamp number rather than a string.
1082 :    
1083 :     =over 4
1084 :    
1085 :     =item id
1086 :    
1087 :     ID to assign to the new entity.
1088 :    
1089 :     =item type
1090 :    
1091 :     Type name for the new entity.
1092 :    
1093 :     =item values
1094 :    
1095 :     Hash containing additional values that might be needed by the data generation methods (optional).
1096 :    
1097 :     =back
1098 :    
1099 :     =cut
1100 :    
1101 :     sub GenerateEntity {
1102 :     # Get the parameters.
1103 :     my $self = shift @_;
1104 :     my ($id, $type, $values) = @_;
1105 :     # Create the return hash.
1106 :     my $this = { id => $id };
1107 :     # Get the metadata structure.
1108 :     my $metadata = $self->{_metaData};
1109 :     # Get this entity's list of fields.
1110 :     if (!exists $metadata->{Entities}->{$type}) {
1111 :     Confess("Unrecognized entity type $type in GenerateEntity.");
1112 :     } else {
1113 :     my $entity = $metadata->{Entities}->{$type};
1114 :     my $fields = $entity->{Fields};
1115 :     # Generate data from the fields.
1116 :     _GenerateFields($this, $fields, $type, $values);
1117 :     }
1118 :     # Return the hash created.
1119 :     return $this;
1120 :     }
1121 :    
1122 :    
1123 :     =head2 Internal Utility Methods
1124 :    
1125 :     =head3 GetLoadStats
1126 :    
1127 :     Return a blank statistics object for use by the load methods.
1128 :    
1129 :     This is a static method.
1130 :    
1131 :     =cut
1132 :    
1133 :     sub _GetLoadStats {
1134 :     return Stats->new('records');
1135 :     }
1136 :    
1137 :     =head3 GenerateFields
1138 :    
1139 :     Generate field values from a field structure and store in a specified table. The field names
1140 :     are first sorted by pass count, certain pre-defined fields are removed from the list, and
1141 :     then we rip through them evaluation the data generation string. Fields in the primary relation
1142 :     are stored as scalars; fields in secondary relations are stored as value lists.
1143 :    
1144 :     This is a static method.
1145 :    
1146 :     =over 4
1147 :    
1148 :     =item this
1149 :    
1150 :     Hash table into which the field values should be placed.
1151 :    
1152 :     =item fields
1153 :    
1154 :     Field structure from which the field descriptors should be taken.
1155 :    
1156 :     =item type
1157 :    
1158 :     Type name of the object whose fields are being generated.
1159 :    
1160 :     =item values (optional)
1161 :    
1162 :     Reference to a value structure from which additional values can be taken.
1163 :    
1164 :     =item from (optiona)
1165 :    
1166 :     Reference to the source entity instance if relationship data is being generated.
1167 :    
1168 :     =item to (optional)
1169 :    
1170 :     Reference to the target entity instance if relationship data is being generated.
1171 :    
1172 :     =back
1173 :    
1174 :     =cut
1175 :    
1176 :     sub _GenerateFields {
1177 :     # Get the parameters.
1178 :     my ($this, $fields, $type, $values, $from, $to) = @_;
1179 :     # Sort the field names by pass number.
1180 :     my @fieldNames = sort { $fields->{$a}->{DataGen}->{pass} <=> $fields->{$b}->{DataGen}->{pass} } keys %{$fields};
1181 :     # Loop through the field names, generating data.
1182 :     for my $name (@fieldNames) {
1183 :     # Only proceed if this field needs to be generated.
1184 :     if (!exists $this->{$name}) {
1185 :     # Get this field's data generation descriptor.
1186 :     my $fieldDescriptor = $fields->{$name};
1187 :     my $data = $fieldDescriptor->{DataGen};
1188 :     # Get the code to generate the field value.
1189 :     my $codeString = $data->{content};
1190 :     # Determine whether or not this field is in the primary relation.
1191 :     if ($fieldDescriptor->{relation} eq $type) {
1192 :     # Here we have a primary relation field. Store the field value as
1193 :     # a scalar.
1194 :     $this->{$name} = eval($codeString);
1195 :     } else {
1196 :     # Here we have a secondary relation field. Create a null list
1197 :     # and push the desired number of field values onto it.
1198 :     my @fieldValues = ();
1199 :     my $count = IntGen(0,$data->{testCount});
1200 :     for (my $i = 0; $i < $count; $i++) {
1201 :     my $newValue = eval($codeString);
1202 :     push @fieldValues, $newValue;
1203 :     }
1204 :     # Store the value list in the main hash.
1205 :     $this->{$name} = \@fieldValues;
1206 :     }
1207 :     }
1208 :     }
1209 :     }
1210 :    
1211 :     =head3 DumpRelation
1212 :    
1213 :     Dump the specified relation's to the specified output file in tab-delimited format.
1214 :    
1215 :     This is an instance method.
1216 :    
1217 :     =over 4
1218 :    
1219 :     =item outputDirectory
1220 :    
1221 :     Directory to contain the output file.
1222 :    
1223 :     =item relationName
1224 :    
1225 :     Name of the relation to dump.
1226 :    
1227 :     =item relation
1228 :    
1229 :     Structure describing the relation to be dumped.
1230 :    
1231 :     =back
1232 :    
1233 :     =cut
1234 :    
1235 :     sub _DumpRelation {
1236 :     # Get the parameters.
1237 :     my $self = shift @_;
1238 :     my ($outputDirectory, $relationName, $relation) = @_;
1239 :     # Open the output file.
1240 :     my $fileName = "$outputDirectory/$relationName.dtx";
1241 :     open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
1242 :     # Create a query for the specified relation.
1243 :     my $dbh = $self->{_dbh};
1244 :     my $query = $dbh->prepare_command("SELECT * FROM $relationName");
1245 :     # Execute the query.
1246 :     $query->execute() || Confess("SELECT error dumping $relationName.");
1247 :     # Loop through the results.
1248 :     while (my @row = $query->fetchrow) {
1249 :     # Escape any tabs or new-lines in the row text.
1250 :     for my $field (@row) {
1251 :     $field =~ s/\n/\\n/g;
1252 :     $field =~ s/\t/\\t/g;
1253 :     }
1254 :     # Tab-join the row and write it to the output file.
1255 :     my $rowText = join("\t", @row);
1256 :     print DTXOUT "$rowText\n";
1257 :     }
1258 :     # Close the output file.
1259 :     close DTXOUT;
1260 :     }
1261 :    
1262 :     =head3 GetStructure
1263 :    
1264 :     Get the data structure for a specified entity or relationship.
1265 :    
1266 :     This is an instance method.
1267 :    
1268 :     =over 4
1269 :    
1270 :     =item objectName
1271 :    
1272 :     Name of the desired entity or relationship.
1273 :    
1274 :     =item RETURN
1275 :    
1276 :     The descriptor for the specified object.
1277 :    
1278 :     =back
1279 :    
1280 :     =cut
1281 :    
1282 :     sub _GetStructure {
1283 :     # Get the parameters.
1284 :     my $self = shift @_;
1285 :     my ($objectName) = @_;
1286 :     # Get the metadata structure.
1287 :     my $metadata = $self->{_metaData};
1288 :     # Declare the variable to receive the descriptor.
1289 :     my $retVal;
1290 :     # Get the descriptor from the metadata.
1291 :     if (exists $metadata->{Entities}->{$objectName}) {
1292 :     $retVal = $metadata->{Entities}->{$objectName};
1293 :     } elsif (exists $metadata->{Relationships}->{$objectName}) {
1294 :     $retVal = $metadata->{Relationships}->{$objectName};
1295 :     } else {
1296 :     Confess("Object $objectName not found in database.");
1297 :     }
1298 :     # Return the descriptor.
1299 :     return $retVal;
1300 :     }
1301 :    
1302 :     =head3 GetRelationTable
1303 :    
1304 :     Get the list of relations for a specified entity or relationship.
1305 :    
1306 :     This is an instance method.
1307 :    
1308 :     =over 4
1309 :    
1310 :     =item objectName
1311 :    
1312 :     Name of the desired entity or relationship.
1313 :    
1314 :     =item RETURN
1315 :    
1316 :     A table containing the relations for the specified object.
1317 :    
1318 :     =back
1319 :    
1320 :     =cut
1321 :    
1322 :     sub _GetRelationTable {
1323 :     # Get the parameters.
1324 :     my $self = shift @_;
1325 :     my ($objectName) = @_;
1326 :     # Get the descriptor from the metadata.
1327 :     my $objectData = $self->_GetStructure($objectName);
1328 :     # Return the object's relation list.
1329 :     return $objectData->{Relations};
1330 :     }
1331 :    
1332 :     =head3 GetFieldTable
1333 :    
1334 :     Get the field structure for a specified entity or relationship.
1335 :    
1336 :     This is an instance method.
1337 :    
1338 :     =over 4
1339 :    
1340 :     =item objectName
1341 :    
1342 :     Name of the desired entity or relationship.
1343 :    
1344 :     =item RETURN
1345 :    
1346 :     The table containing the field descriptors for the specified object.
1347 :    
1348 :     =back
1349 :    
1350 :     =cut
1351 :    
1352 :     sub _GetFieldTable {
1353 :     # Get the parameters.
1354 :     my $self = shift @_;
1355 :     my ($objectName) = @_;
1356 :     # Get the descriptor from the metadata.
1357 :     my $objectData = $self->_GetStructure($objectName);
1358 :     # Return the object's field table.
1359 :     return $objectData->{Fields};
1360 :     }
1361 :    
1362 :     =head3 ValidateFieldNames
1363 :    
1364 :     Determine whether or not the field names are valid. A description of the problems with the names
1365 :     will be written to the standard error output. If there is an error, this method will abort. This is
1366 :     a static method.
1367 :    
1368 :     =over 4
1369 :    
1370 :     =item metadata
1371 :    
1372 :     Metadata structure loaded from the XML data definition.
1373 :    
1374 :     =back
1375 :    
1376 :     =cut
1377 :    
1378 :     sub _ValidateFieldNames {
1379 :     # Get the object.
1380 :     my ($metadata) = @_;
1381 :     # Declare the return value. We assume success.
1382 :     my $retVal = 1;
1383 :     # Loop through the sections of the database definition.
1384 :     for my $section ('Entities', 'Relationships') {
1385 :     # Loop through the objects in this section.
1386 :     for my $object (values %{$metadata->{$section}}) {
1387 :     # Loop through the object's fields.
1388 :     for my $fieldName (keys %{$object->{Fields}}) {
1389 :     # Now we make some initial validations.
1390 :     if ($fieldName =~ /--/) {
1391 :     # Here we have a doubled minus sign.
1392 :     print STDERR "Field name $fieldName has a doubled hyphen.\n";
1393 :     $retVal = 0;
1394 :     } elsif ($fieldName !~ /^[A-Za-z]/) {
1395 :     # Here the field name is missing the initial letter.
1396 :     print STDERR "Field name $fieldName does not begin with a letter.\n";
1397 :     $retVal = 0;
1398 :     } else {
1399 :     # Strip out the minus signs. Everything remaining must be a letter
1400 :     # or digit.
1401 :     my $strippedName = $fieldName;
1402 :     $strippedName =~ s/-//g;
1403 :     if ($strippedName !~ /^[A-Za-z0-9]+$/) {
1404 :     print STDERR "Field name $fieldName contains illegal characters.\n";
1405 :     $retVal = 0;
1406 :     }
1407 :     }
1408 :     }
1409 :     }
1410 :     }
1411 :     # If an error was found, fail.
1412 :     if ($retVal == 0) {
1413 :     Confess("Errors found in field names.");
1414 :     }
1415 :     }
1416 :    
1417 :     =head3 LoadRelation
1418 :    
1419 :     Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk
1420 :     file with the same name as the relation exists in the specified directory.
1421 :    
1422 :     This is an instance method.
1423 :    
1424 :     =over 4
1425 :    
1426 :     =item dbh
1427 :    
1428 :     DBKernel object for accessing the database.
1429 :    
1430 :     =item directoryName
1431 :    
1432 :     Name of the directory containing the tab-delimited data files.
1433 :    
1434 :     =item relationName
1435 :    
1436 :     Name of the relation to load.
1437 :    
1438 :     =item rebuild
1439 :    
1440 :     TRUE if the table should be dropped and re-created before loading.
1441 :    
1442 :     =item RETURN
1443 :    
1444 :     Returns a statistical object describing the number of records read and a list of error messages.
1445 :    
1446 :     =back
1447 :    
1448 :     =cut
1449 :    
1450 :     sub _LoadRelation {
1451 :     # Get the parameters.
1452 :     my $self = shift @_;
1453 :     my ($directoryName, $relationName, $rebuild) = @_;
1454 :     # Create the file name.
1455 :     my $fileName = "$directoryName/$relationName";
1456 :     # If the file doesn't exist, try adding the .dtx suffix.
1457 :     if (! -e $fileName) {
1458 :     $fileName .= ".dtx";
1459 :     if (! -e $fileName) {
1460 :     $fileName = "";
1461 :     }
1462 :     }
1463 :     # Create the return object.
1464 :     my $retVal = _GetLoadStats();
1465 :     # If a file exists to load the table, its name will be in $fileName. Otherwise, $fileName will
1466 :     # be a null string.
1467 :     if ($fileName ne "") {
1468 :     # Load the relation from the file.
1469 :     $retVal = $self->LoadTable($fileName, $relationName, $rebuild);
1470 :     } elsif ($rebuild) {
1471 :     # Here we are rebuilding, but no file exists, so we just re-create the table.
1472 :     $self->CreateTable($relationName, 1);
1473 :     }
1474 :     # Return the statistics from the load.
1475 :     return $retVal;
1476 :     }
1477 :    
1478 :     =head3 LoadMetaData
1479 :    
1480 :     This method loads the data describing this database from an XML file into a metadata structure.
1481 :     The resulting structure is a set of nested hash tables containing all the information needed to
1482 :     load or use the database. The schema for the XML file is F<ERDatabase.xml>.
1483 :    
1484 :     This is a static method.
1485 :    
1486 :     =over 4
1487 :    
1488 :     =item filename
1489 :    
1490 :     Name of the file containing the database definition.
1491 :    
1492 :     =item RETURN
1493 :    
1494 :     Returns a structure describing the database.
1495 :    
1496 :     =back
1497 :    
1498 :     =cut
1499 :    
1500 :     sub _LoadMetaData {
1501 :     # Get the parameters.
1502 :     my ($filename) = @_;
1503 :     # Slurp the XML file into a variable. Extensive use of options is used to insure we
1504 :     # get the exact structure we want.
1505 :     my $metadata = XML::Simple::XMLin($filename,
1506 :     GroupTags => { Relationships => 'Relationship',
1507 :     Entities => 'Entity',
1508 :     Fields => 'Field',
1509 :     Indexes => 'Index',
1510 :     IndexFields => 'IndexField'},
1511 :     KeyAttr => { Relationship => 'name',
1512 :     Entity => 'name',
1513 :     Field => 'name'},
1514 :     ForceArray => ['Field', 'Index', 'IndexField'],
1515 :     ForceContent => 1,
1516 :     NormalizeSpace => 2
1517 :     );
1518 :     Trace("XML metadata loaded from file $filename.") if T(1);
1519 :     # Before we go any farther, we need to validate the field and object names. If an error is found,
1520 :     # the method below will fail.
1521 :     _ValidateFieldNames($metadata);
1522 :     # Next we need to create a hash table for finding relations. The entities and relationships are
1523 :     # implemented as one or more database relations.
1524 :     my %masterRelationTable = ();
1525 :     # Loop through the entities.
1526 :     my $entityList = $metadata->{Entities};
1527 :     while (my ($entityName, $entityStructure) = each %{$entityList}) {
1528 :     #
1529 :     # The first step is to run creating all the entity's default values. For C<Field> elements,
1530 :     # the relation name must be added where it is not specified. For relationships,
1531 :     # the B<from-link> and B<to-link> fields must be inserted, and for entities an B<id>
1532 :     # field must be added to each relation. Finally, each field will have a C<PrettySort> attribute
1533 :     # added that can be used to pull the implicit fields to the top when displaying the field
1534 :     # documentation. The PrettySort values are 1-based and indicate in which pass through a
1535 :     # relation's data the field should be displayed-- 1 for the first pass, 2 for the second,
1536 :     # and so on.
1537 :     #
1538 :     # Fix up this entity.
1539 :     _FixupFields($entityStructure, $entityName, 2, 3);
1540 :     # Add the ID field.
1541 :     _AddField($entityStructure, 'id', { type => $entityStructure->{keyType},
1542 :     relation => $entityName,
1543 :     Notes => { content => "Unique identifier for this \[b\]$entityName\[/b\]." },
1544 :     PrettySort => 1});
1545 :     #
1546 :     # The current field list enables us to quickly find the relation containing a particular field.
1547 :     # We also need a list that tells us the fields in each relation. We do this by creating a
1548 :     # Relations structure in the entity structure and collating the fields into it based on their
1549 :     # C<relation> property. There is one tricky bit, which is that every relation has to have the
1550 :     # C<id> field in it. Note also that the field list is put into a C<Fields> member of the
1551 :     # relation's structure so that it looks more like the entity and relationship structures.
1552 :     #
1553 :     # First we need to create the relations list.
1554 :     my $relationTable = { };
1555 :     # Loop through the fields. We use a list of field names to prevent a problem with
1556 :     # the hash table cursor losing its place during the loop.
1557 :     my $fieldList = $entityStructure->{Fields};
1558 :     my @fieldNames = keys %{$fieldList};
1559 :     for my $fieldName (@fieldNames) {
1560 :     my $fieldData = $fieldList->{$fieldName};
1561 :     # Get the current field's relation name.
1562 :     my $relationName = $fieldData->{relation};
1563 :     # Insure the relation exists.
1564 :     if (!exists $relationTable->{$relationName}) {
1565 :     $relationTable->{$relationName} = { Fields => { } };
1566 :     }
1567 :     # Add the field to the relation's field structure.
1568 :     $relationTable->{$relationName}->{Fields}->{$fieldName} = $fieldData;
1569 :     }
1570 :     # Now that we've organized all our fields by relation name we need to do some serious
1571 :     # housekeeping. We must add the C<id> field to every relation and convert each relation
1572 :     # to a list of fields. First, we need the ID field itself.
1573 :     my $idField = $fieldList->{id};
1574 :     # Loop through the relations.
1575 :     while (my ($relationName, $relation) = each %{$relationTable}) {
1576 :     # Get the relation's field list.
1577 :     my $relationFieldList = $relation->{Fields};
1578 :     # Add the ID field to it. If the field's already there, it will not make any
1579 :     # difference.
1580 :     $relationFieldList->{id} = $idField;
1581 :     # Convert the field set from a hash into a list using the pretty-sort number.
1582 :     $relation->{Fields} = _ReOrderRelationTable($relationFieldList);
1583 :     # Add the relation to the master table.
1584 :     $masterRelationTable{$relationName} = $relation;
1585 :     }
1586 :     # The indexes come next. The primary relation will have a unique-keyed index based on the ID field.
1587 :     # The other relations must have at least one index that begins with the ID field. In addition, the
1588 :     # metadata may require alternate indexes. We do those alternate indexes first. To begin, we need to
1589 :     # get the entity's field list and index list.
1590 :     my $indexList = $entityStructure->{Indexes};
1591 :     # Loop through the indexes.
1592 :     for my $indexData (@{$indexList}) {
1593 :     # We need to find this index's fields. All of them should belong to the same relation.
1594 :     # The ID field is an exception, since it's in all relations.
1595 :     my $relationName = '0';
1596 :     for my $fieldDescriptor (@{$indexData->{IndexFields}}) {
1597 :     # Get this field's name.
1598 :     my $fieldName = $fieldDescriptor->{name};
1599 :     # Only proceed if it is NOT the ID field.
1600 :     if ($fieldName ne 'id') {
1601 :     # Find the relation containing the current index field.
1602 :     my $thisName = $fieldList->{$fieldName}->{relation};
1603 :     if ($relationName eq '0') {
1604 :     # Here we're looking at the first field, so we save its relation name.
1605 :     $relationName = $thisName;
1606 :     } elsif ($relationName ne $thisName) {
1607 :     # Here we have a field mismatch.
1608 :     Confess("Mixed index: field $fieldName does not belong to relation $relationName.");
1609 :     }
1610 :     }
1611 :     }
1612 :     # Now $relationName is the name of the relation that contains this index. Add the index structure
1613 :     # to the relation.
1614 :     push @{$relationTable->{$relationName}->{Indexes}}, $indexData;
1615 :     }
1616 :     # Now each index has been put in a relation. We need to add the primary index for the primary
1617 :     # relation.
1618 :     push @{$relationTable->{$entityName}->{Indexes}},
1619 :     { IndexFields => [ {name => 'id', order => 'ascending'} ], Unique => 'true',
1620 :     Notes => { content => "Primary index for $entityName." }
1621 :     };
1622 :     # The next step is to insure that each relation has at least one index that begins with the ID field.
1623 :     # After that, we convert each relation's index list to an index table. We first need to loop through
1624 :     # the relations.
1625 :     while (my ($relationName, $relation) = each %{$relationTable}) {
1626 :     # Get the relation's index list.
1627 :     my $indexList = $relation->{Indexes};
1628 :     # Insure this relation has an ID index.
1629 :     my $found = 0;
1630 :     for my $index (@{$indexList}) {
1631 :     if ($index->{IndexFields}->[0]->{name} eq "id") {
1632 :     $found = 1;
1633 :     }
1634 :     }
1635 :     if ($found == 0) {
1636 :     push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
1637 :     }
1638 :     # Now we need to convert the relation's index list to an index table. We begin by creating
1639 :     # an empty table in the relation structure.
1640 :     $relation->{Indexes} = { };
1641 :     # Loop through the indexes.
1642 :     my $count = 0;
1643 :     for my $index (@{$indexList}) {
1644 :     # Add this index to the index table.
1645 :     _AddIndex("idx$relationName$count", $relation, $index);
1646 :     # Increment the counter so that the next index has a different name.
1647 :     $count++;
1648 :     }
1649 :     }
1650 :     # Finally, we add the relation structure to the entity.
1651 :     $entityStructure->{Relations} = $relationTable;
1652 :     }
1653 :     # Loop through the relationships. Relationships actually turn out to be much simpler than entities.
1654 :     # For one thing, there is only a single constituent relation.
1655 :     my $relationshipList = $metadata->{Relationships};
1656 :     while (my ($relationshipName, $relationshipStructure) = each %{$relationshipList}) {
1657 :     # Fix up this relationship.
1658 :     _FixupFields($relationshipStructure, $relationshipName, 2, 3);
1659 :     # Format a description for the FROM field.
1660 :     my $fromEntity = $relationshipStructure->{from};
1661 :     my $fromComment = "<b>id</b> of the source <b><a href=\"#$fromEntity\">$fromEntity</a></b>.";
1662 :     # Get the FROM entity's key type.
1663 :     my $fromType = $entityList->{$fromEntity}->{keyType};
1664 :     # Add the FROM field.
1665 :     _AddField($relationshipStructure, 'from-link', { type => $fromType,
1666 :     relation => $relationshipName,
1667 :     Notes => { content => $fromComment },
1668 :     PrettySort => 1});
1669 :     # Format a description for the TO field.
1670 :     my $toEntity = $relationshipStructure->{to};
1671 :     my $toComment = "<b>id</b> of the target <b><a href=\"#$toEntity\">$toEntity</a></b>.";
1672 :     # Get the TO entity's key type.
1673 :     my $toType = $entityList->{$toEntity}->{keyType};
1674 :     # Add the TO field.
1675 :     _AddField($relationshipStructure, 'to-link', { type=> $toType,
1676 :     relation => $relationshipName,
1677 :     Notes => { content => $toComment },
1678 :     PrettySort => 1});
1679 :     # Create an index-free relation from the fields.
1680 :     my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
1681 :     Indexes => { } };
1682 :     $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
1683 :     # Create the FROM and TO indexes.
1684 :     _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
1685 :     _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
1686 :     # Add the relation to the master table.
1687 :     $masterRelationTable{$relationshipName} = $thisRelation;
1688 :     }
1689 :     # Now store the master relation table in the metadata structure.
1690 :     $metadata->{RelationTable} = \%masterRelationTable;
1691 :     # Our final task is to create the join table. The join table is a hash that describes all
1692 :     # the join clauses for traveling through the relationships. The join clause is an equality
1693 :     # condition that can be put into a WHERE clause in order to join two objects. Two relationships
1694 :     # can be joined if they share an entity in common; and an entity can be joined to a relationship
1695 :     # if the entity is at either end of the relationship.
1696 :     my %joinTable = ();
1697 :     # Loop through the entities.
1698 :     for my $entityName (keys %{$entityList}) {
1699 :     # Build three lists of the relationships connected to this entity. One will be
1700 :     # for relationships from the entity, one for relationships to the entity, and
1701 :     # one for recursive relationships.
1702 :     my @fromList = ();
1703 :     my @toList = ();
1704 :     my @bothList = ();
1705 :     while (my ($relationshipName, $relationship) = each %{$relationshipList}) {
1706 :     # Determine if this relationship has our entity in one of its link fields.
1707 :     if ($relationship->{from} eq $entityName) {
1708 :     if ($relationship->{to} eq $entityName) {
1709 :     # Here the relationship is recursive.
1710 :     push @bothList, $relationshipName;
1711 :     } else {
1712 :     # Here the relationship comes from the entity.
1713 :     push @fromList, $relationshipName;
1714 :     }
1715 :     } elsif ($relationship->{to} eq $entityName) {
1716 :     # Here the relationship goes to the entity.
1717 :     push @toList, $relationshipName;
1718 :     }
1719 :     }
1720 :     # Create the nonrecursive joins. Note that we build two hashes for running
1721 :     # through the nonrecursive relationships since we'll have an outer loop
1722 :     # and an inner loop, and we can't do two "each" iterations on the same
1723 :     # hash table at the same time.
1724 :     my %directRelationships = ( from => \@fromList, to => \@toList );
1725 :     my %otherRelationships = ( from => \@fromList, to => \@toList );
1726 :     while (my ($linkType, $relationships) = each %directRelationships) {
1727 :     # Loop through all the relationships.
1728 :     for my $relationshipName (@{$relationships}) {
1729 :     # Create joins between the entity and this relationship.
1730 :     my $linkField = "$relationshipName.${linkType}_link";
1731 :     my $joinClause = "$entityName.id = $linkField";
1732 :     $joinTable{"$entityName/$relationshipName"} = $joinClause;
1733 :     $joinTable{"$relationshipName/$entityName"} = $joinClause;
1734 :     # Create joins between this relationship and the other relationships.
1735 :     while (my ($otherType, $otherships) = each %otherRelationships) {
1736 :     for my $otherName (@{$otherships}) {
1737 :     # Get the key for this join.
1738 :     my $joinKey = "$otherName/$relationshipName";
1739 :     # Check for a duplicate or a self-join.
1740 :     if (exists $joinTable{$joinKey}) {
1741 :     # Here we have a duplicate, which means that the join
1742 :     # path is ambiguous. We delete the join from the join
1743 :     # table to prevent it from being used.
1744 :     delete $joinTable{$joinKey};
1745 :     } elsif ($otherName ne $relationshipName) {
1746 :     # Here we have a valid join. Note that joins between a
1747 :     # relationship and itself are prohibited.
1748 :     $joinTable{$joinKey} = "$otherName.${otherType}_link = $linkField";
1749 :     }
1750 :     }
1751 :     }
1752 :     # Create joins between this relationship and the recursive relationships.
1753 :     # We don't need to check for ambiguous joins here, because a recursive
1754 :     # relationship can only be ambiguous with another recursive relationship,
1755 :     # and the incoming relationship from the outer loop is never recursive.
1756 :     for my $otherName (@bothList) {
1757 :     # Join from the left.
1758 :     $joinTable{"$relationshipName/$otherName"} =
1759 :     "$linkField = $otherName.from_link";
1760 :     # Join from the right.
1761 :     $joinTable{"$otherName/$relationshipName"} =
1762 :     "$otherName.to_link = $linkField";
1763 :     }
1764 :     }
1765 :     }
1766 :     # Create entity joins for the recursive relationships. Unlike the non-recursive
1767 :     # joins, the direction makes a difference with the recursive joins. This can give
1768 :     # rise to situations where we can't create the path we want; however, it is always
1769 :     # possible to get the same effect using multiple queries.
1770 :     for my $relationshipName (@bothList) {
1771 :     # Join to the entity from each direction.
1772 :     $joinTable{"$entityName/$relationshipName"} =
1773 :     "$entityName.id = $relationshipName.from_link";
1774 :     $joinTable{"$relationshipName/$entityName"} =
1775 :     "$relationshipName.to_link = $entityName.id";
1776 :     }
1777 :     }
1778 :     # Add the join table to the structure.
1779 :     $metadata->{Joins} = \%joinTable;
1780 :     # Return the slurped and fixed-up structure.
1781 :     return $metadata;
1782 :     }
1783 :    
1784 :     =head3 CreateRelationshipIndex
1785 :    
1786 :     Create an index for a relationship's relation.
1787 :    
1788 :     This is a static method.
1789 :    
1790 :     =over 4
1791 :    
1792 :     =item indexKey
1793 :    
1794 :     Type of index: either C<"From"> or C<"To">.
1795 :    
1796 :     =item relationshipName
1797 :    
1798 :     Name of the relationship.
1799 :    
1800 :     =item relationshipStructure
1801 :    
1802 :     Structure describing the relationship that the index will sort.
1803 :    
1804 :     =back
1805 :    
1806 :     =cut
1807 :    
1808 :     sub _CreateRelationshipIndex {
1809 :     # Get the parameters.
1810 :     my ($indexKey, $relationshipName, $relationshipStructure) = @_;
1811 :     # Get the target relation.
1812 :     my $relationStructure = $relationshipStructure->{Relations}->{$relationshipName};
1813 :     # Create a descriptor for the link field that goes at the beginning of this index.
1814 :     my $firstField = { name => lcfirst $indexKey . '-link', order => 'ascending' };
1815 :     # Get the target index descriptor.
1816 :     my $newIndex = $relationshipStructure->{$indexKey . "Index"};
1817 :     # Add the first field to the index's field list. Due to the craziness of PERL, if the
1818 :     # index descriptor does not exist, it will be created automatically so we can add
1819 :     # the field to it.
1820 :     unshift @{$newIndex->{IndexFields}}, $firstField;
1821 :     # Add the index to the relation.
1822 :     _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
1823 :     }
1824 :    
1825 :     =head3 AddIndex
1826 :    
1827 :     Add an index to a relation structure.
1828 :    
1829 :     This is a static method.
1830 :    
1831 :     =over 4
1832 :    
1833 :     =item indexName
1834 :    
1835 :     Name to give to the new index.
1836 :    
1837 :     =item relationStructure
1838 :    
1839 :     Relation structure to which the new index should be added.
1840 :    
1841 :     =item newIndex
1842 :    
1843 :     New index to add.
1844 :    
1845 :     =back
1846 :    
1847 :     =cut
1848 :    
1849 :     sub _AddIndex {
1850 :     # Get the parameters.
1851 :     my ($indexName, $relationStructure, $newIndex) = @_;
1852 :     # We want to re-do the index's field list. Instead of an object for each field,
1853 :     # we want a string consisting of the field name optionally followed by the token DESC.
1854 :     my @fieldList = ( );
1855 :     for my $field (@{$newIndex->{IndexFields}}) {
1856 :     # Create a string containing the field name.
1857 :     my $fieldString = $field->{name};
1858 :     # Add the ordering token if needed.
1859 :     if ($field->{order} eq "descending") {
1860 :     $fieldString .= " DESC";
1861 :     }
1862 :     # Push the result onto the field list.
1863 :     push @fieldList, $fieldString;
1864 :     }
1865 :     # Store the field list just created as the new index field list.
1866 :     $newIndex->{IndexFields} = \@fieldList;
1867 :     # Add the index to the relation's index list.
1868 :     $relationStructure->{Indexes}->{$indexName} = $newIndex;
1869 :     }
1870 :    
1871 :     =head3 FixupFields
1872 :    
1873 :     This method fixes the field list for an entity or relationship. It will add the caller-specified
1874 :     relation name to fields that do not have a name and set the C<PrettySort> value as specified.
1875 :    
1876 :     This is a static method.
1877 :    
1878 :     =over 4
1879 :    
1880 :     =item structure
1881 :    
1882 :     Entity or relationship structure to be fixed up.
1883 :    
1884 :     =item defaultRelationName
1885 :    
1886 :     Default relation name to be added to the fields.
1887 :    
1888 :     =item prettySortValue
1889 :    
1890 :     C<PrettySort> value for the relation's normal fields.
1891 :    
1892 :     =item textPrettySortValue
1893 :    
1894 :     C<PrettySort> value for the relation's text fields. This value can be set to one greater than the
1895 :     normal pretty sort value so that text fields go at the end of each relation.
1896 :    
1897 :     =back
1898 :    
1899 :     =cut
1900 :    
1901 :     sub _FixupFields {
1902 :     # Get the parameters.
1903 :     my ($structure, $defaultRelationName, $prettySortValue, $textPrettySortValue) = @_;
1904 :     # Insure the structure has a field list.
1905 :     if (!exists $structure->{Fields}) {
1906 :     # Here it doesn't, so we create a new one.
1907 :     $structure->{Fields} = { };
1908 :     } else {
1909 :     # Here we have a field list. Loop through its fields.
1910 :     while (my ($fieldName, $fieldData) = each %{$structure->{Fields}}) {
1911 :     # Get the field type.
1912 :     my $type = $fieldData->{type};
1913 :     # Plug in a relation name if it is needed.
1914 :     Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
1915 :     # Plug in a data generator if we need one.
1916 :     if (!exists $fieldData->{DataGen}) {
1917 :     # The data generator will use the default for the field's type.
1918 :     $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };
1919 :     }
1920 :     # Plug in the defaults for the optional data generation parameters.
1921 :     Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });
1922 :     # Add the PrettySortValue.
1923 :     $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
1924 :     }
1925 :     }
1926 :     }
1927 :    
1928 :     =head3 FixName
1929 :    
1930 :     Fix the incoming field name so that it is a legal SQL column name.
1931 :    
1932 :     This is a static method.
1933 :    
1934 :     =over 4
1935 :    
1936 :     =item fieldName
1937 :    
1938 :     Field name to fix.
1939 :    
1940 :     =item RETURN
1941 :    
1942 :     Returns the fixed-up field name.
1943 :    
1944 :     =back
1945 :    
1946 :     =cut
1947 :    
1948 :     sub _FixName {
1949 :     # Get the parameter.
1950 :     my ($fieldName) = @_;
1951 :     # Replace its minus signs with underscores.
1952 :     $fieldName =~ s/-/_/g;
1953 :     # Return the result.
1954 :     return $fieldName;
1955 :     }
1956 :    
1957 :     =head3 FixNames
1958 :    
1959 :     Fix all the field names in a list.
1960 :    
1961 :     This is a static method.
1962 :    
1963 :     =over 4
1964 :    
1965 :     =item field1, field2, field3, ... fieldn
1966 :    
1967 :     List of field names to fix.
1968 :    
1969 :     =item RETURN
1970 :    
1971 :     Returns a list of fixed-up versions of the incoming field names.
1972 :    
1973 :     =back
1974 :    
1975 :     =cut
1976 :    
1977 :     sub _FixNames {
1978 :     # Create the result list.
1979 :     my @result = ( );
1980 :     # Loop through the incoming parameters.
1981 :     for my $field (@_) {
1982 :     push @result, _FixName($field);
1983 :     }
1984 :     # Return the result.
1985 :     return @result;
1986 :     }
1987 :    
1988 :     =head3 AddField
1989 :    
1990 :     Add a field to a field list.
1991 :    
1992 :     This is a static method.
1993 :    
1994 :     =over 4
1995 :    
1996 :     =item structure
1997 :    
1998 :     Structure (usually an entity or relationship) that is to contain the field.
1999 :    
2000 :     =item fieldName
2001 :    
2002 :     Name of the new field.
2003 :    
2004 :     =item fieldData
2005 :    
2006 :     Structure containing the data to put in the field.
2007 :    
2008 :     =back
2009 :    
2010 :     =cut
2011 :    
2012 :     sub _AddField {
2013 :     # Get the parameters.
2014 :     my ($structure, $fieldName, $fieldData) = @_;
2015 :     # Create the field structure by copying the incoming data.
2016 :     my $fieldStructure = {%{$fieldData}};
2017 :     # Get a reference to the field list itself.
2018 :     my $fieldList = $structure->{Fields};
2019 :     # Add the field to the field list.
2020 :     $fieldList->{$fieldName} = $fieldStructure;
2021 :     }
2022 :    
2023 :     =head3 ReOrderRelationTable
2024 :    
2025 :     This method will take a relation table and re-sort it according to the implicit ordering of the
2026 :     C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.
2027 :     This requires creating a new hash that contains the field name in the C<name> property but doesn't
2028 :     have the C<PrettySort> property, and then inserting that new hash into the field list.
2029 :    
2030 :     This is a static method.
2031 :    
2032 :     =over 4
2033 :    
2034 :     =item relationTable
2035 :    
2036 :     Relation hash to be reformatted into a list.
2037 :    
2038 :     =item RETURN
2039 :    
2040 :     A list of field hashes.
2041 :    
2042 :     =back
2043 :    
2044 :     =cut
2045 :    
2046 :     sub _ReOrderRelationTable {
2047 :     # Get the parameters.
2048 :     my ($relationTable) = @_;
2049 :     # Create the return list.
2050 :     my @resultList;
2051 :     # Rather than copy all the fields in a single pass, we make multiple passes and only copy
2052 :     # fields whose PrettySort value matches the current pass number. This process continues
2053 :     # until we process all the fields in the relation.
2054 :     my $fieldsLeft = (values %{$relationTable});
2055 :     for (my $sortPass = 1; $fieldsLeft > 0; $sortPass++) {
2056 :     # Loop through the fields. Note that we lexically sort the fields. This makes field name
2057 :     # secondary to pretty-sort number in the final ordering.
2058 :     for my $fieldName (sort keys %{$relationTable}) {
2059 :     # Get this field's data.
2060 :     my $fieldData = $relationTable->{$fieldName};
2061 :     # Verify the sort pass.
2062 :     if ($fieldData->{PrettySort} == $sortPass) {
2063 :     # Here we're in the correct pass. Denote we've found a field.
2064 :     $fieldsLeft--;
2065 :     # The next step is to create the field structure. This done by copying all
2066 :     # of the field elements except PrettySort and adding the name.
2067 :     my %thisField;
2068 :     for my $property (keys %{$fieldData}) {
2069 :     if ($property ne 'PrettySort') {
2070 :     $thisField{$property} = $fieldData->{$property};
2071 :     }
2072 :     }
2073 :     $thisField{name} = $fieldName;
2074 :     # Now we add this field to the end of the result list.
2075 :     push @resultList, \%thisField;
2076 :     }
2077 :     }
2078 :     }
2079 :     # Return a reference to the result list.
2080 :     return \@resultList;
2081 :    
2082 :     }
2083 :    
2084 :     =head3 IsPrimary
2085 :    
2086 :     Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary
2087 :     if it has the same name as an entity or relationship.
2088 :    
2089 :     This is an instance method.
2090 :    
2091 :     =over 4
2092 :    
2093 :     =item relationName
2094 :    
2095 :     Name of the relevant relation.
2096 :    
2097 :     =item RETURN
2098 :    
2099 :     Returns TRUE for a primary relation, else FALSE.
2100 :    
2101 :     =back
2102 :    
2103 :     =cut
2104 :    
2105 :     sub _IsPrimary {
2106 :     # Get the parameters.
2107 :     my $self = shift @_;
2108 :     my ($relationName) = @_;
2109 :     # Check for the relation in the entity table.
2110 :     my $entityTable = $self->{_metaData}->{Entities};
2111 :     my $retVal = exists $entityTable->{$relationName};
2112 :     if (! $retVal) {
2113 :     # Check for it in the relationship table.
2114 :     my $relationshipTable = $self->{_metaData}->{Relationships};
2115 :     $retVal = exists $relationshipTable->{$relationName};
2116 :     }
2117 :     # Return the determination indicator.
2118 :     return $retVal;
2119 :     }
2120 :    
2121 :     =head3 FindRelation
2122 :    
2123 :     Return the descriptor for the specified relation.
2124 :    
2125 :     This is an instance method.
2126 :    
2127 :     =over 4
2128 :    
2129 :     =item relationName
2130 :    
2131 :     Name of the relation whose descriptor is to be returned.
2132 :    
2133 :     =item RETURN
2134 :    
2135 :     Returns the object that describes the relation's indexes and fields.
2136 :    
2137 :     =back
2138 :    
2139 :     =cut
2140 :     sub _FindRelation {
2141 :     # Get the parameters.
2142 :     my $self = shift @_;
2143 :     my ($relationName) = @_;
2144 :     # Get the relation's structure from the master relation table in the metadata structure.
2145 :     my $metaData = $self->{_metaData};
2146 :     my $retVal = $metaData->{RelationTable}->{$relationName};
2147 :     # Return it to the caller.
2148 :     return $retVal;
2149 :     }
2150 :    
2151 :     =head2 HTML Documentation Utility Methods
2152 :    
2153 :     =head3 ComputeRelationshipSentence
2154 :    
2155 :     The relationship sentence consists of the relationship name between the names of the
2156 :     two related entities and an arity indicator.
2157 :    
2158 :     This is a static method.
2159 :    
2160 :     =over 4
2161 :    
2162 :     =item relationshipName
2163 :    
2164 :     Name of the relationship.
2165 :    
2166 :     =item relationshipStructure
2167 :    
2168 :     Relationship structure containing the relationship's description and properties.
2169 :    
2170 :     =item RETURN
2171 :    
2172 :     Returns a string containing the entity names on either side of the relationship name and an
2173 :     indicator of the arity.
2174 :    
2175 :     =back
2176 :    
2177 :     =cut
2178 :    
2179 :     sub _ComputeRelationshipSentence {
2180 :     # Get the parameters.
2181 :     my ($relationshipName, $relationshipStructure) = @_;
2182 :     # Format the relationship sentence.
2183 :     my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";
2184 :     # Compute the arity.
2185 :     my $arityCode = $relationshipStructure->{arity};
2186 :     my $arity = $ArityTable{$arityCode};
2187 :     $result .= " ($arity)";
2188 :     return $result;
2189 :     }
2190 :    
2191 :     =head3 ComputeRelationshipHeading
2192 :    
2193 :     The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
2194 :     names hyperlinked to the appropriate entity sections of the document.
2195 :    
2196 :     This is a static method.
2197 :    
2198 :     =over 4
2199 :    
2200 :     =item relationshipName
2201 :    
2202 :     Name of the relationship.
2203 :    
2204 :     =item relationshipStructure
2205 :    
2206 :     Relationship structure containing the relationship's description and properties.
2207 :    
2208 :     =item RETURN
2209 :    
2210 :     Returns a string containing the entity names on either side of the relationship name with the entity
2211 :     names hyperlinked.
2212 :    
2213 :     =back
2214 :    
2215 :     =cut
2216 :    
2217 :     sub _ComputeRelationshipHeading {
2218 :     # Get the parameters.
2219 :     my ($relationshipName, $relationshipStructure) = @_;
2220 :     # Get the FROM and TO entity names.
2221 :     my $fromEntity = $relationshipStructure->{from};
2222 :     my $toEntity = $relationshipStructure->{to};
2223 :     # Format a relationship sentence with hyperlinks in it.
2224 :     my $result = "<a href=\"#$fromEntity\">$fromEntity</a> $relationshipName <a href=\"#$toEntity\">$toEntity</a>";
2225 :     return $result;
2226 :     }
2227 :    
2228 :     =head3 ShowRelationTable
2229 :    
2230 :     Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
2231 :     table with three columns-- the field name, the field type, and the field description.
2232 :    
2233 :     This is a static method.
2234 :    
2235 :     =over 4
2236 :    
2237 :     =item relationName
2238 :    
2239 :     Name of the relation being formatted.
2240 :    
2241 :     =item relationData
2242 :    
2243 :     Hash containing the relation's fields and indexes.
2244 :    
2245 :     =item RETURN
2246 :    
2247 :     Returns an HTML string that can be used to display the relation name and all of its fields.
2248 :    
2249 :     =back
2250 :    
2251 :     =cut
2252 :    
2253 :     sub _ShowRelationTable {
2254 :     # Get the parameters.
2255 :     my ($relationName, $relationData) = @_;
2256 :     # Start the relation's field table.
2257 :     my $htmlString = _OpenFieldTable($relationName);
2258 :     # Loop through the fields.
2259 :     for my $field (@{$relationData->{Fields}}) {
2260 :     $htmlString .= _ShowField($field);
2261 :     }
2262 :     # Close this relation's field table.
2263 :     $htmlString .= &_CloseTable;
2264 :     # Now we show the relation's indexes.
2265 :     $htmlString .= "<ul>\n";
2266 :     my $indexTable = $relationData->{Indexes};
2267 :     for my $indexName (sort keys %{$indexTable}) {
2268 :     my $indexData = $indexTable->{$indexName};
2269 :     # Determine whether or not the index is unique.
2270 :     my $fullName = $indexName;
2271 :     if ($indexData->{Unique} eq "true") {
2272 :     $fullName .= " (unique)";
2273 :     }
2274 :     # Start an HTML list item for this index.
2275 :     $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
2276 :     # Add any note text.
2277 :     if (my $note = $indexData->{Notes}) {
2278 :     $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";
2279 :     }
2280 :     # Add the fiield list.
2281 :     $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
2282 :     # Close this entry.
2283 :     $htmlString .= "</ul></li>\n";
2284 :     }
2285 :     # Close off the index list.
2286 :     $htmlString .= "</ul>\n";
2287 :     }
2288 :    
2289 :     =head3 OpenFieldTable
2290 :    
2291 :     This method creates the header string for the field table generated by L</ShowMetaData>.
2292 :    
2293 :     This is a static method.
2294 :    
2295 :     =over 4
2296 :    
2297 :     =item tablename
2298 :    
2299 :     Name of the table whose fields will be displayed.
2300 :    
2301 :     =item RETURN
2302 :    
2303 :     Returns a string containing the HTML for a field table's header.
2304 :    
2305 :     =back
2306 :    
2307 :     =cut
2308 :    
2309 :     sub _OpenFieldTable {
2310 :     my ($tablename) = @_;
2311 :     return _OpenTable($tablename, 'Field', 'Type', 'Description');
2312 :     }
2313 :    
2314 :     =head3 OpenTable
2315 :    
2316 :     This method creates the header string for an HTML table.
2317 :    
2318 :     This is a static method.
2319 :    
2320 :     =over 4
2321 :    
2322 :     =item tablename
2323 :    
2324 :     Title of the table.
2325 :    
2326 :     =item colName1, colName2, ..., colNameN
2327 :    
2328 :     List of column names.
2329 :    
2330 :     =item RETURN
2331 :    
2332 :     Returns a string containing the HTML for the desired table's header.
2333 :    
2334 :     =back
2335 :    
2336 :     =cut
2337 :    
2338 :     sub _OpenTable {
2339 :     # Get the parameters.
2340 :     my ($tablename, @colNames) = @_;
2341 :     # Compute the number of columns.
2342 :     my $colCount = @colNames;
2343 :     # Generate the title row.
2344 :     my $htmlString = "<p><table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";
2345 :     # Loop through the columns, adding the column header rows.
2346 :     $htmlString .= "<tr>";
2347 :     for my $colName (@colNames) {
2348 :     $htmlString .= "<th>$colName</th>";
2349 :     }
2350 :     $htmlString .= "</tr>\n";
2351 :     return $htmlString;
2352 :     }
2353 :    
2354 :     =head3 CloseTable
2355 :    
2356 :     This method returns the HTML for closing a table.
2357 :    
2358 :     This is a static method.
2359 :    
2360 :     =cut
2361 :    
2362 :     sub _CloseTable {
2363 :     return "</table></p>\n";
2364 :     }
2365 :    
2366 :     =head3 ShowField
2367 :    
2368 :     This method returns the HTML for displaying a row of field information in a field table.
2369 :    
2370 :     This is a static method.
2371 :    
2372 :     =over 4
2373 :    
2374 :     =item fieldData
2375 :    
2376 :     Table of data about the field.
2377 :    
2378 :     =item RETURN
2379 :    
2380 :     Returns an HTML string for a table row that shows the field's name, type, and description.
2381 :    
2382 :     =back
2383 :    
2384 :     =cut
2385 :    
2386 :     sub _ShowField {
2387 :     # Get the parameters.
2388 :     my ($fieldData) = @_;
2389 :     # Create the HTML string.
2390 :     my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";
2391 :     # If we have content, add it as a third column.
2392 :     if (exists $fieldData->{Notes}) {
2393 :     $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";
2394 :     }
2395 :     # Close off the row.
2396 :     $htmlString .= "</tr>\n";
2397 :     # Return the result.
2398 :     return $htmlString;
2399 :     }
2400 :    
2401 :     =head3 HTMLNote
2402 :    
2403 :     Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
2404 :     supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
2405 :     Except for C<[p]>, all the codes are closed by slash-codes. So, for
2406 :     example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
2407 :    
2408 :     This is a static method.
2409 :    
2410 :     =over 4
2411 :    
2412 :     =item dataString
2413 :    
2414 :     String to convert to HTML.
2415 :    
2416 :     =item RETURN
2417 :    
2418 :     An HTML string derived from the input string.
2419 :    
2420 :     =back
2421 :    
2422 :     =cut
2423 :    
2424 :     sub _HTMLNote {
2425 :     # Get the parameter.
2426 :     my ($dataString) = @_;
2427 :     # Substitute the codes.
2428 :     $dataString =~ s!\[(/?[bi])\]!<$1>!g;
2429 :     $dataString =~ s!\[p\]!</p><p>!g;
2430 :     # Return the result.
2431 :     return $dataString;
2432 :     }
2433 :    
2434 :     =head2 Data Generation Utilities
2435 :    
2436 :     =head3 IntGen
2437 :    
2438 :     C<< my $integer = IntGen($min, $max); >>
2439 :    
2440 :     Returns a random number between the specified minimum and maximum (inclusive).
2441 :    
2442 :     =over 4
2443 :    
2444 :     =item min
2445 :    
2446 :     Minimum permissible return value.
2447 :    
2448 :     =item max
2449 :    
2450 :     Maximum permissible return value.
2451 :    
2452 :     =item RETURN
2453 :    
2454 :     Returns a value no lower than the minimum and no greater than the maximum.
2455 :    
2456 :     =back
2457 :    
2458 :     =cut
2459 :    
2460 :     sub IntGen {
2461 :     # Get the parameters.
2462 :     my ($min, $max) = @_;
2463 :     # Determine the range of possible values. Note we put some space well above the
2464 :     # maximum value to give it a fighting chance of apppearing in the list.
2465 :     my $span = $max + 0.99 - $min;
2466 :     # Create an integer in the range.
2467 :     my $retVal = $min + int(rand($span));
2468 :     # Return the result.
2469 :     return $retVal;
2470 :     }
2471 :    
2472 :     =head3 RandChar
2473 :    
2474 :     C<< my $char = RandChar($sourceString); >>
2475 :    
2476 :     Select a random character from a string.
2477 :    
2478 :     =over 4
2479 :    
2480 :     =item sourceString
2481 :    
2482 :     String from which the random character should be selected.
2483 :    
2484 :     =item RETURN
2485 :    
2486 :     Returns a single character from the incoming string.
2487 :    
2488 :     =back
2489 :    
2490 :     =cut
2491 :    
2492 :     sub RandChar {
2493 :     # Get the parameter.
2494 :     my ($sourceString) = @_;
2495 :     # Select a random character.
2496 :     my $retVal = IntGen(0, (length $sourceString) - 1);
2497 :     # Return it.
2498 :     return substr($sourceString, $retVal, 1);
2499 :     }
2500 :    
2501 :     =head3 RandChars
2502 :    
2503 :     C<< my $string = RandChars($sourceString, $length); >>
2504 :    
2505 :     Create a string from characters taken from a source string.
2506 :    
2507 :     =over 4
2508 :    
2509 :     =item sourceString
2510 :    
2511 :     String from which the random characters should be selected.
2512 :    
2513 :     =item length
2514 :    
2515 :     Number of characters to put in the output string.
2516 :    
2517 :     =item RETURN
2518 :    
2519 :     Returns a string of the specified length consisting of characters taken from the
2520 :     source string.
2521 :    
2522 :     =back
2523 :    
2524 :     =cut
2525 :    
2526 :     sub RandChars {
2527 :     # Get the parameters.
2528 :     my ($sourceString, $length) = @_;
2529 :     # Call RandChar repeatedly to generate the string.
2530 :     my $retVal = "";
2531 :     for (my $i = 0; $i < $length; $i++) {
2532 :     $retVal .= RandChar($sourceString);
2533 :     }
2534 :     # Return the result.
2535 :     return $retVal;
2536 :     }
2537 :    
2538 :     =head3 RandParam
2539 :    
2540 :     C<< my $value = RandParam($parm1, $parm2, ... $parmN); >>
2541 :    
2542 :     Return a randomly-selected value from the parameter list.
2543 :    
2544 :     =over 4
2545 :    
2546 :     =item parm1, parm2, ... parmN
2547 :    
2548 :     List of values of which one will be selected.
2549 :    
2550 :     =item RETURN
2551 :    
2552 :     Returns a randomly-chosen value from the specified list.
2553 :    
2554 :     =back
2555 :    
2556 :     =cut
2557 :    
2558 :     sub RandParam {
2559 :     # Get the parameter.
2560 :     my @parms = @_;
2561 :     # Choose a random parameter from the list.
2562 :     my $chosenIndex = IntGen(0, $#parms);
2563 :     return $parms[$chosenIndex];
2564 :     }
2565 :    
2566 :     =head3 StringGen
2567 :    
2568 :     C<< my $string = StringGen($pattern1, $pattern2, ... $patternN); >>
2569 :    
2570 :     Returns a random string derived from a randomly-chosen format pattern. The pattern
2571 :     can either be a number (indicating the number of characters desired, or the letter
2572 :     C<P> followed by a picture. The picture should contain C<A> when a letter is desired,
2573 :     C<9> when a digit is desired, C<V> when a vowel is desired, C<K> when a consonant is
2574 :     desired, and C<X> when a letter or a digit is desired. Any other character will be
2575 :     translated as a literal.
2576 :    
2577 :     =over 4
2578 :    
2579 :     =item pattern1, pattern2, ... patternN
2580 :    
2581 :     List of patterns to be used to generate string values.
2582 :    
2583 :     =item RETURN
2584 :    
2585 :     A single string generated from a pattern.
2586 :    
2587 :     =back
2588 :    
2589 :     =cut
2590 :    
2591 :     sub StringGen {
2592 :     # Get the parameters.
2593 :     my @patterns = @_;
2594 :     # Choose the appropriate pattern.
2595 :     my $chosenPattern = RandParam(@patterns);
2596 :     # Declare the return variable.
2597 :     my $retVal = "";
2598 :     # Determine whether this is a count or a picture pattern.
2599 :     if ($chosenPattern =~ m/^\d+/) {
2600 :     # Here we have a count. Get the string of source characters.
2601 :     my $letterString = $PictureTable{'X'};
2602 :     my $stringLen = length $letterString;
2603 :     # Save the number of characters we have to generate.
2604 :     my $charsLeft = $chosenPattern;
2605 :     # Loop until the return variable is full.
2606 :     while ($charsLeft > 0) {
2607 :     # Generate a random position in the soruce string.
2608 :     my $stringIndex = IntGen(0, $stringLen - 1);
2609 :     # Compute the number of characters to pull out of the source string.
2610 :     my $chunkSize = $stringLen - $stringIndex;
2611 :     if ($chunkSize > $charsLeft) { $chunkSize = $charsLeft; }
2612 :     # Stuff this chunk into the return value.
2613 :     $retVal .= substr($letterString, $stringIndex, $chunkSize);
2614 :     # Record the data moved.
2615 :     $charsLeft -= $chunkSize;
2616 :     }
2617 :     } elsif ($chosenPattern =~ m/^P/) {
2618 :     # Here we have a picture string. We will move through the picture one
2619 :     # character at a time generating data.
2620 :     for (my $i = 1; $i < length $chosenPattern; $i++) {
2621 :     # Get this picture character.
2622 :     my $chr = substr($chosenPattern, $i, 1);
2623 :     # Check to see if the picture char is one we recognize.
2624 :     if (exists $PictureTable{$chr}) {
2625 :     # Choose a random character from the available values for this
2626 :     # picture character.
2627 :     $retVal .= RandChar($PictureTable{$chr});
2628 :     } else {
2629 :     # Copy in the picture character as a literal.
2630 :     $retVal .= $chr;
2631 :     }
2632 :     }
2633 :     } else {
2634 :     # Here we have neither a picture string or a letter count, so we treat
2635 :     # the string as a literal.
2636 :     $retVal = $chosenPattern;
2637 :     }
2638 :     # Return the string formed.
2639 :     return $retVal;
2640 :     }
2641 :    
2642 :     =head3 DateGen
2643 :    
2644 :     C<< my $date = DateGen($startDayOffset, $endDayOffset, $minutes); >>
2645 :    
2646 :     Return a numeric timestamp within the specified range of days with the specified minute
2647 :     value. The range of days is specified relevant to the current day. Thus, the call
2648 :    
2649 :     C<< my $date = DateGen(-1, 5, 720); >>
2650 :    
2651 :     will return a timestamp at noon (72 minutes past midnight) sometime during the week that
2652 :     began on the preceding day. If you want a random minute of the day, simply combine with
2653 :     a call to L</IntGen>, as follows.
2654 :    
2655 :     C<< my $date = DateGen(-1, 5, IntGen(0, 1439)); >>
2656 :    
2657 :     =over 4
2658 :    
2659 :     =item startDayOffset
2660 :    
2661 :     The earliest day that can be returned, relative to the current day.
2662 :    
2663 :     =item endDayOffset
2664 :    
2665 :     The latest day that can be returned, related to the current day.
2666 :    
2667 :     =item minutes
2668 :    
2669 :     Number of minutes into the selected day that should be used.
2670 :    
2671 :     =back
2672 :    
2673 :     =cut
2674 :    
2675 :     sub DateGen {
2676 :     # Get the parameters.
2677 :     my ($startDayOffset, $endDayOffset, $minutes) = @_;
2678 :     # Get midnight of the current day.
2679 :     my $now = time();
2680 :     my ($sec, $min, $hour) = localtime($now);
2681 :     my $today = $now - (($hour * 60 + $min) * 60 + $sec);
2682 :     # Compute the day we want.
2683 :     my $newDay = IntGen($startDayOffset, $endDayOffset) * 86400 + $today;
2684 :     # Add the minutes.
2685 :     my $retVal = $newDay + $minutes * 60;
2686 :     # Return the result.
2687 :     return $retVal;
2688 :     }
2689 :    
2690 :     =head3 FloatGen
2691 :    
2692 :     C<< my $number = FloatGen($min, $max); >>
2693 :    
2694 :     Return a random floating-point number greater than or equal to the specified minimum and
2695 :     less than the specified maximum.
2696 :    
2697 :     =over 4
2698 :    
2699 :     =item min
2700 :    
2701 :     Minimum permissible value for the number returned.
2702 :    
2703 :     =item max
2704 :    
2705 :     Maximum permissible value for the number returned.
2706 :    
2707 :     =item RETURN
2708 :    
2709 :     Returns a floating-point number anywhere in the specified range.
2710 :    
2711 :     =back
2712 :    
2713 :     =cut
2714 :    
2715 :     sub FloatGen {
2716 :     # Get the parameters.
2717 :     my ($min, $max) = @_;
2718 :     # Generate the result.
2719 :     my $retVal = rand($max - $min) + $min;
2720 :     return $retVal;
2721 :     }
2722 :    
2723 :     =head3 ListGen
2724 :    
2725 :     C<< my @list = ListGen($pattern, $count); >>
2726 :    
2727 :     Return a list containing a fixed number of randomly-generated strings.
2728 :    
2729 :     =over 4
2730 :    
2731 :     =item pattern
2732 :    
2733 :     A pattern (in the form expected by L</StringGen>) that should be used to generate the
2734 :     strings in the list.
2735 :    
2736 :     =item count
2737 :    
2738 :     The number of list entries to generate.
2739 :    
2740 :     =item RETURN
2741 :    
2742 :     Returns a list consisting of the specified number of strings.
2743 :    
2744 :     =back
2745 :    
2746 :     =cut
2747 :    
2748 :     sub ListGen {
2749 :     # Get the parameters.
2750 :     my ($pattern, $count) = @_;
2751 :     # Generate the list.
2752 :     my @retVal = ();
2753 :     for (my $i = 0; $i < $count; $i++) {
2754 :     push @retVal, StringGen($pattern);
2755 :     }
2756 :     # Return it.
2757 :     return @retVal;
2758 :     }
2759 :    
2760 :     1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3