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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.3 - (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 : parrello 1.2 user needs to start with an empty database. Otherwise, the L</LoadTables> method can be
317 : parrello 1.1 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 : parrello 1.2 my $relationData = $self->_FindRelation($relationName);
421 : parrello 1.1 # 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 : parrello 1.2 # Only proceed if the record is non-blank.
1020 :     if ($record) {
1021 :     # Escape all the backslashes found in the line.
1022 :     $record =~ s/\\/\\\\/g;
1023 :     # Eliminate any trailing tabs.
1024 :     chop $record while substr($record, -1) eq "\t";
1025 :     # If this is a primary relation, add a 0 for the new-record flag (indicating that
1026 :     # this record is not new, but part of the original load).
1027 :     if ($primary) {
1028 :     $record .= "\t0";
1029 :     }
1030 :     # Write the record.
1031 :     print TABLEOUT "$record\n";
1032 :     # Count the record read.
1033 :     my $count = $retVal->Add('records');
1034 : parrello 1.3 my $len = length $record;
1035 :     Trace("Record $count written with $len characters.") if T(4);
1036 : parrello 1.2 }
1037 : parrello 1.1 }
1038 :     # Close the files.
1039 :     close TABLEIN;
1040 :     close TABLEOUT;
1041 : parrello 1.3 Trace("Temporary file $tempName created.") if T(4);
1042 :     # Load the table.
1043 : parrello 1.1 my $rv;
1044 :     eval {
1045 :     $rv = $dbh->load_table(file => $tempName, tbl => $relationName);
1046 :     };
1047 :     if (!defined $rv) {
1048 : parrello 1.3 $retVal->AddMessage($@) if ($@);
1049 :     $retVal->AddMessage("Table load failed for $relationName using $tempName.");
1050 : parrello 1.1 Trace("Table load failed for $relationName.") if T(1);
1051 :     } else {
1052 :     # Here we successfully loaded the table. Trace the number of records loaded.
1053 :     Trace("$retVal->{records} records read for $relationName.") if T(1);
1054 :     # If we're rebuilding, we need to create the table indexes.
1055 :     if ($truncateFlag) {
1056 :     eval {
1057 :     $self->CreateIndex($relationName);
1058 :     };
1059 :     if ($@) {
1060 :     $retVal->AddMessage($@);
1061 :     }
1062 : parrello 1.2 }
1063 : parrello 1.1 }
1064 :     # Commit the database changes.
1065 :     $dbh->commit_tran;
1066 :     # Delete the temporary file.
1067 :     unlink $tempName;
1068 :     # Return the statistics.
1069 :     return $retVal;
1070 :     }
1071 :    
1072 :     =head3 GenerateEntity
1073 :    
1074 :     C<< my $fieldHash = $database->GenerateEntity($id, $type, \%values); >>
1075 :    
1076 :     Generate the data for a new entity instance. This method creates a field hash suitable for
1077 :     passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest
1078 :     of the fields are generated using information in the database schema.
1079 :    
1080 :     Each data type has a default algorithm for generating random test data. This can be overridden
1081 :     by including a B<DataGen> element in the field. If this happens, the content of the element is
1082 :     executed as a PERL program in the context of this module. The element may make use of a C<$this>
1083 :     variable which contains the field hash as it has been built up to the current point. If any
1084 :     fields are dependent on other fields, the C<pass> attribute can be used to control the order
1085 :     in which the fields are generated. A field with a high data pass number will be generated after
1086 :     a field with a lower one. If any external values are needed, they should be passed in via the
1087 :     optional third parameter, which will be available to the data generation script under the name
1088 :     C<$value>. Several useful utility methods are provided for generating random values, including
1089 :     L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated
1090 :     in the form of a timestamp number rather than a string.
1091 :    
1092 :     =over 4
1093 :    
1094 :     =item id
1095 :    
1096 :     ID to assign to the new entity.
1097 :    
1098 :     =item type
1099 :    
1100 :     Type name for the new entity.
1101 :    
1102 :     =item values
1103 :    
1104 :     Hash containing additional values that might be needed by the data generation methods (optional).
1105 :    
1106 :     =back
1107 :    
1108 :     =cut
1109 :    
1110 :     sub GenerateEntity {
1111 :     # Get the parameters.
1112 :     my $self = shift @_;
1113 :     my ($id, $type, $values) = @_;
1114 :     # Create the return hash.
1115 :     my $this = { id => $id };
1116 :     # Get the metadata structure.
1117 :     my $metadata = $self->{_metaData};
1118 :     # Get this entity's list of fields.
1119 :     if (!exists $metadata->{Entities}->{$type}) {
1120 :     Confess("Unrecognized entity type $type in GenerateEntity.");
1121 :     } else {
1122 :     my $entity = $metadata->{Entities}->{$type};
1123 :     my $fields = $entity->{Fields};
1124 :     # Generate data from the fields.
1125 :     _GenerateFields($this, $fields, $type, $values);
1126 :     }
1127 :     # Return the hash created.
1128 :     return $this;
1129 :     }
1130 :    
1131 :    
1132 :     =head2 Internal Utility Methods
1133 :    
1134 :     =head3 GetLoadStats
1135 :    
1136 :     Return a blank statistics object for use by the load methods.
1137 :    
1138 :     This is a static method.
1139 :    
1140 :     =cut
1141 :    
1142 :     sub _GetLoadStats {
1143 :     return Stats->new('records');
1144 :     }
1145 :    
1146 :     =head3 GenerateFields
1147 :    
1148 :     Generate field values from a field structure and store in a specified table. The field names
1149 :     are first sorted by pass count, certain pre-defined fields are removed from the list, and
1150 :     then we rip through them evaluation the data generation string. Fields in the primary relation
1151 :     are stored as scalars; fields in secondary relations are stored as value lists.
1152 :    
1153 :     This is a static method.
1154 :    
1155 :     =over 4
1156 :    
1157 :     =item this
1158 :    
1159 :     Hash table into which the field values should be placed.
1160 :    
1161 :     =item fields
1162 :    
1163 :     Field structure from which the field descriptors should be taken.
1164 :    
1165 :     =item type
1166 :    
1167 :     Type name of the object whose fields are being generated.
1168 :    
1169 :     =item values (optional)
1170 :    
1171 :     Reference to a value structure from which additional values can be taken.
1172 :    
1173 :     =item from (optiona)
1174 :    
1175 :     Reference to the source entity instance if relationship data is being generated.
1176 :    
1177 :     =item to (optional)
1178 :    
1179 :     Reference to the target entity instance if relationship data is being generated.
1180 :    
1181 :     =back
1182 :    
1183 :     =cut
1184 :    
1185 :     sub _GenerateFields {
1186 :     # Get the parameters.
1187 :     my ($this, $fields, $type, $values, $from, $to) = @_;
1188 :     # Sort the field names by pass number.
1189 :     my @fieldNames = sort { $fields->{$a}->{DataGen}->{pass} <=> $fields->{$b}->{DataGen}->{pass} } keys %{$fields};
1190 :     # Loop through the field names, generating data.
1191 :     for my $name (@fieldNames) {
1192 :     # Only proceed if this field needs to be generated.
1193 :     if (!exists $this->{$name}) {
1194 :     # Get this field's data generation descriptor.
1195 :     my $fieldDescriptor = $fields->{$name};
1196 :     my $data = $fieldDescriptor->{DataGen};
1197 :     # Get the code to generate the field value.
1198 :     my $codeString = $data->{content};
1199 :     # Determine whether or not this field is in the primary relation.
1200 :     if ($fieldDescriptor->{relation} eq $type) {
1201 :     # Here we have a primary relation field. Store the field value as
1202 :     # a scalar.
1203 :     $this->{$name} = eval($codeString);
1204 :     } else {
1205 :     # Here we have a secondary relation field. Create a null list
1206 :     # and push the desired number of field values onto it.
1207 :     my @fieldValues = ();
1208 :     my $count = IntGen(0,$data->{testCount});
1209 :     for (my $i = 0; $i < $count; $i++) {
1210 :     my $newValue = eval($codeString);
1211 :     push @fieldValues, $newValue;
1212 :     }
1213 :     # Store the value list in the main hash.
1214 :     $this->{$name} = \@fieldValues;
1215 :     }
1216 :     }
1217 :     }
1218 :     }
1219 :    
1220 :     =head3 DumpRelation
1221 :    
1222 :     Dump the specified relation's to the specified output file in tab-delimited format.
1223 :    
1224 :     This is an instance method.
1225 :    
1226 :     =over 4
1227 :    
1228 :     =item outputDirectory
1229 :    
1230 :     Directory to contain the output file.
1231 :    
1232 :     =item relationName
1233 :    
1234 :     Name of the relation to dump.
1235 :    
1236 :     =item relation
1237 :    
1238 :     Structure describing the relation to be dumped.
1239 :    
1240 :     =back
1241 :    
1242 :     =cut
1243 :    
1244 :     sub _DumpRelation {
1245 :     # Get the parameters.
1246 :     my $self = shift @_;
1247 :     my ($outputDirectory, $relationName, $relation) = @_;
1248 :     # Open the output file.
1249 :     my $fileName = "$outputDirectory/$relationName.dtx";
1250 :     open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
1251 :     # Create a query for the specified relation.
1252 :     my $dbh = $self->{_dbh};
1253 :     my $query = $dbh->prepare_command("SELECT * FROM $relationName");
1254 :     # Execute the query.
1255 :     $query->execute() || Confess("SELECT error dumping $relationName.");
1256 :     # Loop through the results.
1257 :     while (my @row = $query->fetchrow) {
1258 :     # Escape any tabs or new-lines in the row text.
1259 :     for my $field (@row) {
1260 :     $field =~ s/\n/\\n/g;
1261 :     $field =~ s/\t/\\t/g;
1262 :     }
1263 :     # Tab-join the row and write it to the output file.
1264 :     my $rowText = join("\t", @row);
1265 :     print DTXOUT "$rowText\n";
1266 :     }
1267 :     # Close the output file.
1268 :     close DTXOUT;
1269 :     }
1270 :    
1271 :     =head3 GetStructure
1272 :    
1273 :     Get the data structure for a specified entity or relationship.
1274 :    
1275 :     This is an instance method.
1276 :    
1277 :     =over 4
1278 :    
1279 :     =item objectName
1280 :    
1281 :     Name of the desired entity or relationship.
1282 :    
1283 :     =item RETURN
1284 :    
1285 :     The descriptor for the specified object.
1286 :    
1287 :     =back
1288 :    
1289 :     =cut
1290 :    
1291 :     sub _GetStructure {
1292 :     # Get the parameters.
1293 :     my $self = shift @_;
1294 :     my ($objectName) = @_;
1295 :     # Get the metadata structure.
1296 :     my $metadata = $self->{_metaData};
1297 :     # Declare the variable to receive the descriptor.
1298 :     my $retVal;
1299 :     # Get the descriptor from the metadata.
1300 :     if (exists $metadata->{Entities}->{$objectName}) {
1301 :     $retVal = $metadata->{Entities}->{$objectName};
1302 :     } elsif (exists $metadata->{Relationships}->{$objectName}) {
1303 :     $retVal = $metadata->{Relationships}->{$objectName};
1304 :     } else {
1305 :     Confess("Object $objectName not found in database.");
1306 :     }
1307 :     # Return the descriptor.
1308 :     return $retVal;
1309 :     }
1310 :    
1311 :     =head3 GetRelationTable
1312 :    
1313 :     Get the list of relations for a specified entity or relationship.
1314 :    
1315 :     This is an instance method.
1316 :    
1317 :     =over 4
1318 :    
1319 :     =item objectName
1320 :    
1321 :     Name of the desired entity or relationship.
1322 :    
1323 :     =item RETURN
1324 :    
1325 :     A table containing the relations for the specified object.
1326 :    
1327 :     =back
1328 :    
1329 :     =cut
1330 :    
1331 :     sub _GetRelationTable {
1332 :     # Get the parameters.
1333 :     my $self = shift @_;
1334 :     my ($objectName) = @_;
1335 :     # Get the descriptor from the metadata.
1336 :     my $objectData = $self->_GetStructure($objectName);
1337 :     # Return the object's relation list.
1338 :     return $objectData->{Relations};
1339 :     }
1340 :    
1341 :     =head3 GetFieldTable
1342 :    
1343 :     Get the field structure for a specified entity or relationship.
1344 :    
1345 :     This is an instance method.
1346 :    
1347 :     =over 4
1348 :    
1349 :     =item objectName
1350 :    
1351 :     Name of the desired entity or relationship.
1352 :    
1353 :     =item RETURN
1354 :    
1355 :     The table containing the field descriptors for the specified object.
1356 :    
1357 :     =back
1358 :    
1359 :     =cut
1360 :    
1361 :     sub _GetFieldTable {
1362 :     # Get the parameters.
1363 :     my $self = shift @_;
1364 :     my ($objectName) = @_;
1365 :     # Get the descriptor from the metadata.
1366 :     my $objectData = $self->_GetStructure($objectName);
1367 :     # Return the object's field table.
1368 :     return $objectData->{Fields};
1369 :     }
1370 :    
1371 :     =head3 ValidateFieldNames
1372 :    
1373 :     Determine whether or not the field names are valid. A description of the problems with the names
1374 :     will be written to the standard error output. If there is an error, this method will abort. This is
1375 :     a static method.
1376 :    
1377 :     =over 4
1378 :    
1379 :     =item metadata
1380 :    
1381 :     Metadata structure loaded from the XML data definition.
1382 :    
1383 :     =back
1384 :    
1385 :     =cut
1386 :    
1387 :     sub _ValidateFieldNames {
1388 :     # Get the object.
1389 :     my ($metadata) = @_;
1390 :     # Declare the return value. We assume success.
1391 :     my $retVal = 1;
1392 :     # Loop through the sections of the database definition.
1393 :     for my $section ('Entities', 'Relationships') {
1394 :     # Loop through the objects in this section.
1395 :     for my $object (values %{$metadata->{$section}}) {
1396 :     # Loop through the object's fields.
1397 :     for my $fieldName (keys %{$object->{Fields}}) {
1398 :     # Now we make some initial validations.
1399 :     if ($fieldName =~ /--/) {
1400 :     # Here we have a doubled minus sign.
1401 :     print STDERR "Field name $fieldName has a doubled hyphen.\n";
1402 :     $retVal = 0;
1403 :     } elsif ($fieldName !~ /^[A-Za-z]/) {
1404 :     # Here the field name is missing the initial letter.
1405 :     print STDERR "Field name $fieldName does not begin with a letter.\n";
1406 :     $retVal = 0;
1407 :     } else {
1408 :     # Strip out the minus signs. Everything remaining must be a letter
1409 :     # or digit.
1410 :     my $strippedName = $fieldName;
1411 :     $strippedName =~ s/-//g;
1412 :     if ($strippedName !~ /^[A-Za-z0-9]+$/) {
1413 :     print STDERR "Field name $fieldName contains illegal characters.\n";
1414 :     $retVal = 0;
1415 :     }
1416 :     }
1417 :     }
1418 :     }
1419 :     }
1420 :     # If an error was found, fail.
1421 :     if ($retVal == 0) {
1422 :     Confess("Errors found in field names.");
1423 :     }
1424 :     }
1425 :    
1426 :     =head3 LoadRelation
1427 :    
1428 :     Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk
1429 :     file with the same name as the relation exists in the specified directory.
1430 :    
1431 :     This is an instance method.
1432 :    
1433 :     =over 4
1434 :    
1435 :     =item dbh
1436 :    
1437 :     DBKernel object for accessing the database.
1438 :    
1439 :     =item directoryName
1440 :    
1441 :     Name of the directory containing the tab-delimited data files.
1442 :    
1443 :     =item relationName
1444 :    
1445 :     Name of the relation to load.
1446 :    
1447 :     =item rebuild
1448 :    
1449 :     TRUE if the table should be dropped and re-created before loading.
1450 :    
1451 :     =item RETURN
1452 :    
1453 :     Returns a statistical object describing the number of records read and a list of error messages.
1454 :    
1455 :     =back
1456 :    
1457 :     =cut
1458 :    
1459 :     sub _LoadRelation {
1460 :     # Get the parameters.
1461 :     my $self = shift @_;
1462 :     my ($directoryName, $relationName, $rebuild) = @_;
1463 :     # Create the file name.
1464 :     my $fileName = "$directoryName/$relationName";
1465 :     # If the file doesn't exist, try adding the .dtx suffix.
1466 :     if (! -e $fileName) {
1467 :     $fileName .= ".dtx";
1468 :     if (! -e $fileName) {
1469 :     $fileName = "";
1470 :     }
1471 :     }
1472 :     # Create the return object.
1473 :     my $retVal = _GetLoadStats();
1474 :     # If a file exists to load the table, its name will be in $fileName. Otherwise, $fileName will
1475 :     # be a null string.
1476 :     if ($fileName ne "") {
1477 :     # Load the relation from the file.
1478 :     $retVal = $self->LoadTable($fileName, $relationName, $rebuild);
1479 :     } elsif ($rebuild) {
1480 :     # Here we are rebuilding, but no file exists, so we just re-create the table.
1481 :     $self->CreateTable($relationName, 1);
1482 :     }
1483 :     # Return the statistics from the load.
1484 :     return $retVal;
1485 :     }
1486 :    
1487 :     =head3 LoadMetaData
1488 :    
1489 :     This method loads the data describing this database from an XML file into a metadata structure.
1490 :     The resulting structure is a set of nested hash tables containing all the information needed to
1491 :     load or use the database. The schema for the XML file is F<ERDatabase.xml>.
1492 :    
1493 :     This is a static method.
1494 :    
1495 :     =over 4
1496 :    
1497 :     =item filename
1498 :    
1499 :     Name of the file containing the database definition.
1500 :    
1501 :     =item RETURN
1502 :    
1503 :     Returns a structure describing the database.
1504 :    
1505 :     =back
1506 :    
1507 :     =cut
1508 :    
1509 :     sub _LoadMetaData {
1510 :     # Get the parameters.
1511 :     my ($filename) = @_;
1512 :     # Slurp the XML file into a variable. Extensive use of options is used to insure we
1513 :     # get the exact structure we want.
1514 :     my $metadata = XML::Simple::XMLin($filename,
1515 :     GroupTags => { Relationships => 'Relationship',
1516 :     Entities => 'Entity',
1517 :     Fields => 'Field',
1518 :     Indexes => 'Index',
1519 :     IndexFields => 'IndexField'},
1520 :     KeyAttr => { Relationship => 'name',
1521 :     Entity => 'name',
1522 :     Field => 'name'},
1523 :     ForceArray => ['Field', 'Index', 'IndexField'],
1524 :     ForceContent => 1,
1525 :     NormalizeSpace => 2
1526 :     );
1527 :     Trace("XML metadata loaded from file $filename.") if T(1);
1528 :     # Before we go any farther, we need to validate the field and object names. If an error is found,
1529 :     # the method below will fail.
1530 :     _ValidateFieldNames($metadata);
1531 :     # Next we need to create a hash table for finding relations. The entities and relationships are
1532 :     # implemented as one or more database relations.
1533 :     my %masterRelationTable = ();
1534 :     # Loop through the entities.
1535 :     my $entityList = $metadata->{Entities};
1536 :     while (my ($entityName, $entityStructure) = each %{$entityList}) {
1537 :     #
1538 :     # The first step is to run creating all the entity's default values. For C<Field> elements,
1539 :     # the relation name must be added where it is not specified. For relationships,
1540 :     # the B<from-link> and B<to-link> fields must be inserted, and for entities an B<id>
1541 :     # field must be added to each relation. Finally, each field will have a C<PrettySort> attribute
1542 :     # added that can be used to pull the implicit fields to the top when displaying the field
1543 :     # documentation. The PrettySort values are 1-based and indicate in which pass through a
1544 :     # relation's data the field should be displayed-- 1 for the first pass, 2 for the second,
1545 :     # and so on.
1546 :     #
1547 :     # Fix up this entity.
1548 :     _FixupFields($entityStructure, $entityName, 2, 3);
1549 :     # Add the ID field.
1550 :     _AddField($entityStructure, 'id', { type => $entityStructure->{keyType},
1551 :     relation => $entityName,
1552 :     Notes => { content => "Unique identifier for this \[b\]$entityName\[/b\]." },
1553 :     PrettySort => 1});
1554 :     #
1555 :     # The current field list enables us to quickly find the relation containing a particular field.
1556 :     # We also need a list that tells us the fields in each relation. We do this by creating a
1557 :     # Relations structure in the entity structure and collating the fields into it based on their
1558 :     # C<relation> property. There is one tricky bit, which is that every relation has to have the
1559 :     # C<id> field in it. Note also that the field list is put into a C<Fields> member of the
1560 :     # relation's structure so that it looks more like the entity and relationship structures.
1561 :     #
1562 :     # First we need to create the relations list.
1563 :     my $relationTable = { };
1564 :     # Loop through the fields. We use a list of field names to prevent a problem with
1565 :     # the hash table cursor losing its place during the loop.
1566 :     my $fieldList = $entityStructure->{Fields};
1567 :     my @fieldNames = keys %{$fieldList};
1568 :     for my $fieldName (@fieldNames) {
1569 :     my $fieldData = $fieldList->{$fieldName};
1570 :     # Get the current field's relation name.
1571 :     my $relationName = $fieldData->{relation};
1572 :     # Insure the relation exists.
1573 :     if (!exists $relationTable->{$relationName}) {
1574 :     $relationTable->{$relationName} = { Fields => { } };
1575 :     }
1576 :     # Add the field to the relation's field structure.
1577 :     $relationTable->{$relationName}->{Fields}->{$fieldName} = $fieldData;
1578 :     }
1579 :     # Now that we've organized all our fields by relation name we need to do some serious
1580 :     # housekeeping. We must add the C<id> field to every relation and convert each relation
1581 :     # to a list of fields. First, we need the ID field itself.
1582 :     my $idField = $fieldList->{id};
1583 :     # Loop through the relations.
1584 :     while (my ($relationName, $relation) = each %{$relationTable}) {
1585 :     # Get the relation's field list.
1586 :     my $relationFieldList = $relation->{Fields};
1587 :     # Add the ID field to it. If the field's already there, it will not make any
1588 :     # difference.
1589 :     $relationFieldList->{id} = $idField;
1590 :     # Convert the field set from a hash into a list using the pretty-sort number.
1591 :     $relation->{Fields} = _ReOrderRelationTable($relationFieldList);
1592 :     # Add the relation to the master table.
1593 :     $masterRelationTable{$relationName} = $relation;
1594 :     }
1595 :     # The indexes come next. The primary relation will have a unique-keyed index based on the ID field.
1596 :     # The other relations must have at least one index that begins with the ID field. In addition, the
1597 :     # metadata may require alternate indexes. We do those alternate indexes first. To begin, we need to
1598 :     # get the entity's field list and index list.
1599 :     my $indexList = $entityStructure->{Indexes};
1600 :     # Loop through the indexes.
1601 :     for my $indexData (@{$indexList}) {
1602 :     # We need to find this index's fields. All of them should belong to the same relation.
1603 :     # The ID field is an exception, since it's in all relations.
1604 :     my $relationName = '0';
1605 :     for my $fieldDescriptor (@{$indexData->{IndexFields}}) {
1606 :     # Get this field's name.
1607 :     my $fieldName = $fieldDescriptor->{name};
1608 :     # Only proceed if it is NOT the ID field.
1609 :     if ($fieldName ne 'id') {
1610 :     # Find the relation containing the current index field.
1611 :     my $thisName = $fieldList->{$fieldName}->{relation};
1612 :     if ($relationName eq '0') {
1613 :     # Here we're looking at the first field, so we save its relation name.
1614 :     $relationName = $thisName;
1615 :     } elsif ($relationName ne $thisName) {
1616 :     # Here we have a field mismatch.
1617 :     Confess("Mixed index: field $fieldName does not belong to relation $relationName.");
1618 :     }
1619 :     }
1620 :     }
1621 :     # Now $relationName is the name of the relation that contains this index. Add the index structure
1622 :     # to the relation.
1623 :     push @{$relationTable->{$relationName}->{Indexes}}, $indexData;
1624 :     }
1625 :     # Now each index has been put in a relation. We need to add the primary index for the primary
1626 :     # relation.
1627 :     push @{$relationTable->{$entityName}->{Indexes}},
1628 :     { IndexFields => [ {name => 'id', order => 'ascending'} ], Unique => 'true',
1629 :     Notes => { content => "Primary index for $entityName." }
1630 :     };
1631 :     # The next step is to insure that each relation has at least one index that begins with the ID field.
1632 :     # After that, we convert each relation's index list to an index table. We first need to loop through
1633 :     # the relations.
1634 :     while (my ($relationName, $relation) = each %{$relationTable}) {
1635 :     # Get the relation's index list.
1636 :     my $indexList = $relation->{Indexes};
1637 :     # Insure this relation has an ID index.
1638 :     my $found = 0;
1639 :     for my $index (@{$indexList}) {
1640 :     if ($index->{IndexFields}->[0]->{name} eq "id") {
1641 :     $found = 1;
1642 :     }
1643 :     }
1644 :     if ($found == 0) {
1645 :     push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
1646 :     }
1647 :     # Now we need to convert the relation's index list to an index table. We begin by creating
1648 :     # an empty table in the relation structure.
1649 :     $relation->{Indexes} = { };
1650 :     # Loop through the indexes.
1651 :     my $count = 0;
1652 :     for my $index (@{$indexList}) {
1653 :     # Add this index to the index table.
1654 :     _AddIndex("idx$relationName$count", $relation, $index);
1655 :     # Increment the counter so that the next index has a different name.
1656 :     $count++;
1657 :     }
1658 :     }
1659 :     # Finally, we add the relation structure to the entity.
1660 :     $entityStructure->{Relations} = $relationTable;
1661 :     }
1662 :     # Loop through the relationships. Relationships actually turn out to be much simpler than entities.
1663 :     # For one thing, there is only a single constituent relation.
1664 :     my $relationshipList = $metadata->{Relationships};
1665 :     while (my ($relationshipName, $relationshipStructure) = each %{$relationshipList}) {
1666 :     # Fix up this relationship.
1667 :     _FixupFields($relationshipStructure, $relationshipName, 2, 3);
1668 :     # Format a description for the FROM field.
1669 :     my $fromEntity = $relationshipStructure->{from};
1670 :     my $fromComment = "<b>id</b> of the source <b><a href=\"#$fromEntity\">$fromEntity</a></b>.";
1671 :     # Get the FROM entity's key type.
1672 :     my $fromType = $entityList->{$fromEntity}->{keyType};
1673 :     # Add the FROM field.
1674 :     _AddField($relationshipStructure, 'from-link', { type => $fromType,
1675 :     relation => $relationshipName,
1676 :     Notes => { content => $fromComment },
1677 :     PrettySort => 1});
1678 :     # Format a description for the TO field.
1679 :     my $toEntity = $relationshipStructure->{to};
1680 :     my $toComment = "<b>id</b> of the target <b><a href=\"#$toEntity\">$toEntity</a></b>.";
1681 :     # Get the TO entity's key type.
1682 :     my $toType = $entityList->{$toEntity}->{keyType};
1683 :     # Add the TO field.
1684 :     _AddField($relationshipStructure, 'to-link', { type=> $toType,
1685 :     relation => $relationshipName,
1686 :     Notes => { content => $toComment },
1687 :     PrettySort => 1});
1688 :     # Create an index-free relation from the fields.
1689 :     my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
1690 :     Indexes => { } };
1691 :     $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
1692 :     # Create the FROM and TO indexes.
1693 :     _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
1694 :     _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
1695 :     # Add the relation to the master table.
1696 :     $masterRelationTable{$relationshipName} = $thisRelation;
1697 :     }
1698 :     # Now store the master relation table in the metadata structure.
1699 :     $metadata->{RelationTable} = \%masterRelationTable;
1700 :     # Our final task is to create the join table. The join table is a hash that describes all
1701 :     # the join clauses for traveling through the relationships. The join clause is an equality
1702 :     # condition that can be put into a WHERE clause in order to join two objects. Two relationships
1703 :     # can be joined if they share an entity in common; and an entity can be joined to a relationship
1704 :     # if the entity is at either end of the relationship.
1705 :     my %joinTable = ();
1706 :     # Loop through the entities.
1707 :     for my $entityName (keys %{$entityList}) {
1708 :     # Build three lists of the relationships connected to this entity. One will be
1709 :     # for relationships from the entity, one for relationships to the entity, and
1710 :     # one for recursive relationships.
1711 :     my @fromList = ();
1712 :     my @toList = ();
1713 :     my @bothList = ();
1714 :     while (my ($relationshipName, $relationship) = each %{$relationshipList}) {
1715 :     # Determine if this relationship has our entity in one of its link fields.
1716 :     if ($relationship->{from} eq $entityName) {
1717 :     if ($relationship->{to} eq $entityName) {
1718 :     # Here the relationship is recursive.
1719 :     push @bothList, $relationshipName;
1720 :     } else {
1721 :     # Here the relationship comes from the entity.
1722 :     push @fromList, $relationshipName;
1723 :     }
1724 :     } elsif ($relationship->{to} eq $entityName) {
1725 :     # Here the relationship goes to the entity.
1726 :     push @toList, $relationshipName;
1727 :     }
1728 :     }
1729 :     # Create the nonrecursive joins. Note that we build two hashes for running
1730 :     # through the nonrecursive relationships since we'll have an outer loop
1731 :     # and an inner loop, and we can't do two "each" iterations on the same
1732 :     # hash table at the same time.
1733 :     my %directRelationships = ( from => \@fromList, to => \@toList );
1734 :     my %otherRelationships = ( from => \@fromList, to => \@toList );
1735 :     while (my ($linkType, $relationships) = each %directRelationships) {
1736 :     # Loop through all the relationships.
1737 :     for my $relationshipName (@{$relationships}) {
1738 :     # Create joins between the entity and this relationship.
1739 :     my $linkField = "$relationshipName.${linkType}_link";
1740 :     my $joinClause = "$entityName.id = $linkField";
1741 :     $joinTable{"$entityName/$relationshipName"} = $joinClause;
1742 :     $joinTable{"$relationshipName/$entityName"} = $joinClause;
1743 :     # Create joins between this relationship and the other relationships.
1744 :     while (my ($otherType, $otherships) = each %otherRelationships) {
1745 :     for my $otherName (@{$otherships}) {
1746 :     # Get the key for this join.
1747 :     my $joinKey = "$otherName/$relationshipName";
1748 :     # Check for a duplicate or a self-join.
1749 :     if (exists $joinTable{$joinKey}) {
1750 :     # Here we have a duplicate, which means that the join
1751 :     # path is ambiguous. We delete the join from the join
1752 :     # table to prevent it from being used.
1753 :     delete $joinTable{$joinKey};
1754 :     } elsif ($otherName ne $relationshipName) {
1755 :     # Here we have a valid join. Note that joins between a
1756 :     # relationship and itself are prohibited.
1757 :     $joinTable{$joinKey} = "$otherName.${otherType}_link = $linkField";
1758 :     }
1759 :     }
1760 :     }
1761 :     # Create joins between this relationship and the recursive relationships.
1762 :     # We don't need to check for ambiguous joins here, because a recursive
1763 :     # relationship can only be ambiguous with another recursive relationship,
1764 :     # and the incoming relationship from the outer loop is never recursive.
1765 :     for my $otherName (@bothList) {
1766 :     # Join from the left.
1767 :     $joinTable{"$relationshipName/$otherName"} =
1768 :     "$linkField = $otherName.from_link";
1769 :     # Join from the right.
1770 :     $joinTable{"$otherName/$relationshipName"} =
1771 :     "$otherName.to_link = $linkField";
1772 :     }
1773 :     }
1774 :     }
1775 :     # Create entity joins for the recursive relationships. Unlike the non-recursive
1776 :     # joins, the direction makes a difference with the recursive joins. This can give
1777 :     # rise to situations where we can't create the path we want; however, it is always
1778 :     # possible to get the same effect using multiple queries.
1779 :     for my $relationshipName (@bothList) {
1780 :     # Join to the entity from each direction.
1781 :     $joinTable{"$entityName/$relationshipName"} =
1782 :     "$entityName.id = $relationshipName.from_link";
1783 :     $joinTable{"$relationshipName/$entityName"} =
1784 :     "$relationshipName.to_link = $entityName.id";
1785 :     }
1786 :     }
1787 :     # Add the join table to the structure.
1788 :     $metadata->{Joins} = \%joinTable;
1789 :     # Return the slurped and fixed-up structure.
1790 :     return $metadata;
1791 :     }
1792 :    
1793 :     =head3 CreateRelationshipIndex
1794 :    
1795 :     Create an index for a relationship's relation.
1796 :    
1797 :     This is a static method.
1798 :    
1799 :     =over 4
1800 :    
1801 :     =item indexKey
1802 :    
1803 :     Type of index: either C<"From"> or C<"To">.
1804 :    
1805 :     =item relationshipName
1806 :    
1807 :     Name of the relationship.
1808 :    
1809 :     =item relationshipStructure
1810 :    
1811 :     Structure describing the relationship that the index will sort.
1812 :    
1813 :     =back
1814 :    
1815 :     =cut
1816 :    
1817 :     sub _CreateRelationshipIndex {
1818 :     # Get the parameters.
1819 :     my ($indexKey, $relationshipName, $relationshipStructure) = @_;
1820 :     # Get the target relation.
1821 :     my $relationStructure = $relationshipStructure->{Relations}->{$relationshipName};
1822 :     # Create a descriptor for the link field that goes at the beginning of this index.
1823 :     my $firstField = { name => lcfirst $indexKey . '-link', order => 'ascending' };
1824 :     # Get the target index descriptor.
1825 :     my $newIndex = $relationshipStructure->{$indexKey . "Index"};
1826 :     # Add the first field to the index's field list. Due to the craziness of PERL, if the
1827 :     # index descriptor does not exist, it will be created automatically so we can add
1828 :     # the field to it.
1829 :     unshift @{$newIndex->{IndexFields}}, $firstField;
1830 :     # Add the index to the relation.
1831 :     _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
1832 :     }
1833 :    
1834 :     =head3 AddIndex
1835 :    
1836 :     Add an index to a relation structure.
1837 :    
1838 :     This is a static method.
1839 :    
1840 :     =over 4
1841 :    
1842 :     =item indexName
1843 :    
1844 :     Name to give to the new index.
1845 :    
1846 :     =item relationStructure
1847 :    
1848 :     Relation structure to which the new index should be added.
1849 :    
1850 :     =item newIndex
1851 :    
1852 :     New index to add.
1853 :    
1854 :     =back
1855 :    
1856 :     =cut
1857 :    
1858 :     sub _AddIndex {
1859 :     # Get the parameters.
1860 :     my ($indexName, $relationStructure, $newIndex) = @_;
1861 :     # We want to re-do the index's field list. Instead of an object for each field,
1862 :     # we want a string consisting of the field name optionally followed by the token DESC.
1863 :     my @fieldList = ( );
1864 :     for my $field (@{$newIndex->{IndexFields}}) {
1865 :     # Create a string containing the field name.
1866 :     my $fieldString = $field->{name};
1867 :     # Add the ordering token if needed.
1868 :     if ($field->{order} eq "descending") {
1869 :     $fieldString .= " DESC";
1870 :     }
1871 :     # Push the result onto the field list.
1872 :     push @fieldList, $fieldString;
1873 :     }
1874 :     # Store the field list just created as the new index field list.
1875 :     $newIndex->{IndexFields} = \@fieldList;
1876 :     # Add the index to the relation's index list.
1877 :     $relationStructure->{Indexes}->{$indexName} = $newIndex;
1878 :     }
1879 :    
1880 :     =head3 FixupFields
1881 :    
1882 :     This method fixes the field list for an entity or relationship. It will add the caller-specified
1883 :     relation name to fields that do not have a name and set the C<PrettySort> value as specified.
1884 :    
1885 :     This is a static method.
1886 :    
1887 :     =over 4
1888 :    
1889 :     =item structure
1890 :    
1891 :     Entity or relationship structure to be fixed up.
1892 :    
1893 :     =item defaultRelationName
1894 :    
1895 :     Default relation name to be added to the fields.
1896 :    
1897 :     =item prettySortValue
1898 :    
1899 :     C<PrettySort> value for the relation's normal fields.
1900 :    
1901 :     =item textPrettySortValue
1902 :    
1903 :     C<PrettySort> value for the relation's text fields. This value can be set to one greater than the
1904 :     normal pretty sort value so that text fields go at the end of each relation.
1905 :    
1906 :     =back
1907 :    
1908 :     =cut
1909 :    
1910 :     sub _FixupFields {
1911 :     # Get the parameters.
1912 :     my ($structure, $defaultRelationName, $prettySortValue, $textPrettySortValue) = @_;
1913 :     # Insure the structure has a field list.
1914 :     if (!exists $structure->{Fields}) {
1915 :     # Here it doesn't, so we create a new one.
1916 :     $structure->{Fields} = { };
1917 :     } else {
1918 :     # Here we have a field list. Loop through its fields.
1919 :     while (my ($fieldName, $fieldData) = each %{$structure->{Fields}}) {
1920 :     # Get the field type.
1921 :     my $type = $fieldData->{type};
1922 :     # Plug in a relation name if it is needed.
1923 :     Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
1924 :     # Plug in a data generator if we need one.
1925 :     if (!exists $fieldData->{DataGen}) {
1926 :     # The data generator will use the default for the field's type.
1927 :     $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };
1928 :     }
1929 :     # Plug in the defaults for the optional data generation parameters.
1930 :     Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });
1931 :     # Add the PrettySortValue.
1932 :     $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
1933 :     }
1934 :     }
1935 :     }
1936 :    
1937 :     =head3 FixName
1938 :    
1939 :     Fix the incoming field name so that it is a legal SQL column name.
1940 :    
1941 :     This is a static method.
1942 :    
1943 :     =over 4
1944 :    
1945 :     =item fieldName
1946 :    
1947 :     Field name to fix.
1948 :    
1949 :     =item RETURN
1950 :    
1951 :     Returns the fixed-up field name.
1952 :    
1953 :     =back
1954 :    
1955 :     =cut
1956 :    
1957 :     sub _FixName {
1958 :     # Get the parameter.
1959 :     my ($fieldName) = @_;
1960 :     # Replace its minus signs with underscores.
1961 :     $fieldName =~ s/-/_/g;
1962 :     # Return the result.
1963 :     return $fieldName;
1964 :     }
1965 :    
1966 :     =head3 FixNames
1967 :    
1968 :     Fix all the field names in a list.
1969 :    
1970 :     This is a static method.
1971 :    
1972 :     =over 4
1973 :    
1974 :     =item field1, field2, field3, ... fieldn
1975 :    
1976 :     List of field names to fix.
1977 :    
1978 :     =item RETURN
1979 :    
1980 :     Returns a list of fixed-up versions of the incoming field names.
1981 :    
1982 :     =back
1983 :    
1984 :     =cut
1985 :    
1986 :     sub _FixNames {
1987 :     # Create the result list.
1988 :     my @result = ( );
1989 :     # Loop through the incoming parameters.
1990 :     for my $field (@_) {
1991 :     push @result, _FixName($field);
1992 :     }
1993 :     # Return the result.
1994 :     return @result;
1995 :     }
1996 :    
1997 :     =head3 AddField
1998 :    
1999 :     Add a field to a field list.
2000 :    
2001 :     This is a static method.
2002 :    
2003 :     =over 4
2004 :    
2005 :     =item structure
2006 :    
2007 :     Structure (usually an entity or relationship) that is to contain the field.
2008 :    
2009 :     =item fieldName
2010 :    
2011 :     Name of the new field.
2012 :    
2013 :     =item fieldData
2014 :    
2015 :     Structure containing the data to put in the field.
2016 :    
2017 :     =back
2018 :    
2019 :     =cut
2020 :    
2021 :     sub _AddField {
2022 :     # Get the parameters.
2023 :     my ($structure, $fieldName, $fieldData) = @_;
2024 :     # Create the field structure by copying the incoming data.
2025 :     my $fieldStructure = {%{$fieldData}};
2026 :     # Get a reference to the field list itself.
2027 :     my $fieldList = $structure->{Fields};
2028 :     # Add the field to the field list.
2029 :     $fieldList->{$fieldName} = $fieldStructure;
2030 :     }
2031 :    
2032 :     =head3 ReOrderRelationTable
2033 :    
2034 :     This method will take a relation table and re-sort it according to the implicit ordering of the
2035 :     C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.
2036 :     This requires creating a new hash that contains the field name in the C<name> property but doesn't
2037 :     have the C<PrettySort> property, and then inserting that new hash into the field list.
2038 :    
2039 :     This is a static method.
2040 :    
2041 :     =over 4
2042 :    
2043 :     =item relationTable
2044 :    
2045 :     Relation hash to be reformatted into a list.
2046 :    
2047 :     =item RETURN
2048 :    
2049 :     A list of field hashes.
2050 :    
2051 :     =back
2052 :    
2053 :     =cut
2054 :    
2055 :     sub _ReOrderRelationTable {
2056 :     # Get the parameters.
2057 :     my ($relationTable) = @_;
2058 :     # Create the return list.
2059 :     my @resultList;
2060 :     # Rather than copy all the fields in a single pass, we make multiple passes and only copy
2061 :     # fields whose PrettySort value matches the current pass number. This process continues
2062 :     # until we process all the fields in the relation.
2063 :     my $fieldsLeft = (values %{$relationTable});
2064 :     for (my $sortPass = 1; $fieldsLeft > 0; $sortPass++) {
2065 :     # Loop through the fields. Note that we lexically sort the fields. This makes field name
2066 :     # secondary to pretty-sort number in the final ordering.
2067 :     for my $fieldName (sort keys %{$relationTable}) {
2068 :     # Get this field's data.
2069 :     my $fieldData = $relationTable->{$fieldName};
2070 :     # Verify the sort pass.
2071 :     if ($fieldData->{PrettySort} == $sortPass) {
2072 :     # Here we're in the correct pass. Denote we've found a field.
2073 :     $fieldsLeft--;
2074 :     # The next step is to create the field structure. This done by copying all
2075 :     # of the field elements except PrettySort and adding the name.
2076 :     my %thisField;
2077 :     for my $property (keys %{$fieldData}) {
2078 :     if ($property ne 'PrettySort') {
2079 :     $thisField{$property} = $fieldData->{$property};
2080 :     }
2081 :     }
2082 :     $thisField{name} = $fieldName;
2083 :     # Now we add this field to the end of the result list.
2084 :     push @resultList, \%thisField;
2085 :     }
2086 :     }
2087 :     }
2088 :     # Return a reference to the result list.
2089 :     return \@resultList;
2090 :    
2091 :     }
2092 :    
2093 :     =head3 IsPrimary
2094 :    
2095 :     Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary
2096 :     if it has the same name as an entity or relationship.
2097 :    
2098 :     This is an instance method.
2099 :    
2100 :     =over 4
2101 :    
2102 :     =item relationName
2103 :    
2104 :     Name of the relevant relation.
2105 :    
2106 :     =item RETURN
2107 :    
2108 :     Returns TRUE for a primary relation, else FALSE.
2109 :    
2110 :     =back
2111 :    
2112 :     =cut
2113 :    
2114 :     sub _IsPrimary {
2115 :     # Get the parameters.
2116 :     my $self = shift @_;
2117 :     my ($relationName) = @_;
2118 :     # Check for the relation in the entity table.
2119 :     my $entityTable = $self->{_metaData}->{Entities};
2120 :     my $retVal = exists $entityTable->{$relationName};
2121 :     if (! $retVal) {
2122 :     # Check for it in the relationship table.
2123 :     my $relationshipTable = $self->{_metaData}->{Relationships};
2124 :     $retVal = exists $relationshipTable->{$relationName};
2125 :     }
2126 :     # Return the determination indicator.
2127 :     return $retVal;
2128 :     }
2129 :    
2130 :     =head3 FindRelation
2131 :    
2132 :     Return the descriptor for the specified relation.
2133 :    
2134 :     This is an instance method.
2135 :    
2136 :     =over 4
2137 :    
2138 :     =item relationName
2139 :    
2140 :     Name of the relation whose descriptor is to be returned.
2141 :    
2142 :     =item RETURN
2143 :    
2144 :     Returns the object that describes the relation's indexes and fields.
2145 :    
2146 :     =back
2147 :    
2148 :     =cut
2149 :     sub _FindRelation {
2150 :     # Get the parameters.
2151 :     my $self = shift @_;
2152 :     my ($relationName) = @_;
2153 :     # Get the relation's structure from the master relation table in the metadata structure.
2154 :     my $metaData = $self->{_metaData};
2155 :     my $retVal = $metaData->{RelationTable}->{$relationName};
2156 :     # Return it to the caller.
2157 :     return $retVal;
2158 :     }
2159 :    
2160 :     =head2 HTML Documentation Utility Methods
2161 :    
2162 :     =head3 ComputeRelationshipSentence
2163 :    
2164 :     The relationship sentence consists of the relationship name between the names of the
2165 :     two related entities and an arity indicator.
2166 :    
2167 :     This is a static method.
2168 :    
2169 :     =over 4
2170 :    
2171 :     =item relationshipName
2172 :    
2173 :     Name of the relationship.
2174 :    
2175 :     =item relationshipStructure
2176 :    
2177 :     Relationship structure containing the relationship's description and properties.
2178 :    
2179 :     =item RETURN
2180 :    
2181 :     Returns a string containing the entity names on either side of the relationship name and an
2182 :     indicator of the arity.
2183 :    
2184 :     =back
2185 :    
2186 :     =cut
2187 :    
2188 :     sub _ComputeRelationshipSentence {
2189 :     # Get the parameters.
2190 :     my ($relationshipName, $relationshipStructure) = @_;
2191 :     # Format the relationship sentence.
2192 :     my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";
2193 :     # Compute the arity.
2194 :     my $arityCode = $relationshipStructure->{arity};
2195 :     my $arity = $ArityTable{$arityCode};
2196 :     $result .= " ($arity)";
2197 :     return $result;
2198 :     }
2199 :    
2200 :     =head3 ComputeRelationshipHeading
2201 :    
2202 :     The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
2203 :     names hyperlinked to the appropriate entity sections of the document.
2204 :    
2205 :     This is a static method.
2206 :    
2207 :     =over 4
2208 :    
2209 :     =item relationshipName
2210 :    
2211 :     Name of the relationship.
2212 :    
2213 :     =item relationshipStructure
2214 :    
2215 :     Relationship structure containing the relationship's description and properties.
2216 :    
2217 :     =item RETURN
2218 :    
2219 :     Returns a string containing the entity names on either side of the relationship name with the entity
2220 :     names hyperlinked.
2221 :    
2222 :     =back
2223 :    
2224 :     =cut
2225 :    
2226 :     sub _ComputeRelationshipHeading {
2227 :     # Get the parameters.
2228 :     my ($relationshipName, $relationshipStructure) = @_;
2229 :     # Get the FROM and TO entity names.
2230 :     my $fromEntity = $relationshipStructure->{from};
2231 :     my $toEntity = $relationshipStructure->{to};
2232 :     # Format a relationship sentence with hyperlinks in it.
2233 :     my $result = "<a href=\"#$fromEntity\">$fromEntity</a> $relationshipName <a href=\"#$toEntity\">$toEntity</a>";
2234 :     return $result;
2235 :     }
2236 :    
2237 :     =head3 ShowRelationTable
2238 :    
2239 :     Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
2240 :     table with three columns-- the field name, the field type, and the field description.
2241 :    
2242 :     This is a static method.
2243 :    
2244 :     =over 4
2245 :    
2246 :     =item relationName
2247 :    
2248 :     Name of the relation being formatted.
2249 :    
2250 :     =item relationData
2251 :    
2252 :     Hash containing the relation's fields and indexes.
2253 :    
2254 :     =item RETURN
2255 :    
2256 :     Returns an HTML string that can be used to display the relation name and all of its fields.
2257 :    
2258 :     =back
2259 :    
2260 :     =cut
2261 :    
2262 :     sub _ShowRelationTable {
2263 :     # Get the parameters.
2264 :     my ($relationName, $relationData) = @_;
2265 :     # Start the relation's field table.
2266 :     my $htmlString = _OpenFieldTable($relationName);
2267 :     # Loop through the fields.
2268 :     for my $field (@{$relationData->{Fields}}) {
2269 :     $htmlString .= _ShowField($field);
2270 :     }
2271 :     # Close this relation's field table.
2272 :     $htmlString .= &_CloseTable;
2273 :     # Now we show the relation's indexes.
2274 :     $htmlString .= "<ul>\n";
2275 :     my $indexTable = $relationData->{Indexes};
2276 :     for my $indexName (sort keys %{$indexTable}) {
2277 :     my $indexData = $indexTable->{$indexName};
2278 :     # Determine whether or not the index is unique.
2279 :     my $fullName = $indexName;
2280 :     if ($indexData->{Unique} eq "true") {
2281 :     $fullName .= " (unique)";
2282 :     }
2283 :     # Start an HTML list item for this index.
2284 :     $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
2285 :     # Add any note text.
2286 :     if (my $note = $indexData->{Notes}) {
2287 :     $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";
2288 :     }
2289 :     # Add the fiield list.
2290 :     $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
2291 :     # Close this entry.
2292 :     $htmlString .= "</ul></li>\n";
2293 :     }
2294 :     # Close off the index list.
2295 :     $htmlString .= "</ul>\n";
2296 :     }
2297 :    
2298 :     =head3 OpenFieldTable
2299 :    
2300 :     This method creates the header string for the field table generated by L</ShowMetaData>.
2301 :    
2302 :     This is a static method.
2303 :    
2304 :     =over 4
2305 :    
2306 :     =item tablename
2307 :    
2308 :     Name of the table whose fields will be displayed.
2309 :    
2310 :     =item RETURN
2311 :    
2312 :     Returns a string containing the HTML for a field table's header.
2313 :    
2314 :     =back
2315 :    
2316 :     =cut
2317 :    
2318 :     sub _OpenFieldTable {
2319 :     my ($tablename) = @_;
2320 :     return _OpenTable($tablename, 'Field', 'Type', 'Description');
2321 :     }
2322 :    
2323 :     =head3 OpenTable
2324 :    
2325 :     This method creates the header string for an HTML table.
2326 :    
2327 :     This is a static method.
2328 :    
2329 :     =over 4
2330 :    
2331 :     =item tablename
2332 :    
2333 :     Title of the table.
2334 :    
2335 :     =item colName1, colName2, ..., colNameN
2336 :    
2337 :     List of column names.
2338 :    
2339 :     =item RETURN
2340 :    
2341 :     Returns a string containing the HTML for the desired table's header.
2342 :    
2343 :     =back
2344 :    
2345 :     =cut
2346 :    
2347 :     sub _OpenTable {
2348 :     # Get the parameters.
2349 :     my ($tablename, @colNames) = @_;
2350 :     # Compute the number of columns.
2351 :     my $colCount = @colNames;
2352 :     # Generate the title row.
2353 :     my $htmlString = "<p><table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";
2354 :     # Loop through the columns, adding the column header rows.
2355 :     $htmlString .= "<tr>";
2356 :     for my $colName (@colNames) {
2357 :     $htmlString .= "<th>$colName</th>";
2358 :     }
2359 :     $htmlString .= "</tr>\n";
2360 :     return $htmlString;
2361 :     }
2362 :    
2363 :     =head3 CloseTable
2364 :    
2365 :     This method returns the HTML for closing a table.
2366 :    
2367 :     This is a static method.
2368 :    
2369 :     =cut
2370 :    
2371 :     sub _CloseTable {
2372 :     return "</table></p>\n";
2373 :     }
2374 :    
2375 :     =head3 ShowField
2376 :    
2377 :     This method returns the HTML for displaying a row of field information in a field table.
2378 :    
2379 :     This is a static method.
2380 :    
2381 :     =over 4
2382 :    
2383 :     =item fieldData
2384 :    
2385 :     Table of data about the field.
2386 :    
2387 :     =item RETURN
2388 :    
2389 :     Returns an HTML string for a table row that shows the field's name, type, and description.
2390 :    
2391 :     =back
2392 :    
2393 :     =cut
2394 :    
2395 :     sub _ShowField {
2396 :     # Get the parameters.
2397 :     my ($fieldData) = @_;
2398 :     # Create the HTML string.
2399 :     my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";
2400 :     # If we have content, add it as a third column.
2401 :     if (exists $fieldData->{Notes}) {
2402 :     $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";
2403 :     }
2404 :     # Close off the row.
2405 :     $htmlString .= "</tr>\n";
2406 :     # Return the result.
2407 :     return $htmlString;
2408 :     }
2409 :    
2410 :     =head3 HTMLNote
2411 :    
2412 :     Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
2413 :     supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
2414 :     Except for C<[p]>, all the codes are closed by slash-codes. So, for
2415 :     example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
2416 :    
2417 :     This is a static method.
2418 :    
2419 :     =over 4
2420 :    
2421 :     =item dataString
2422 :    
2423 :     String to convert to HTML.
2424 :    
2425 :     =item RETURN
2426 :    
2427 :     An HTML string derived from the input string.
2428 :    
2429 :     =back
2430 :    
2431 :     =cut
2432 :    
2433 :     sub _HTMLNote {
2434 :     # Get the parameter.
2435 :     my ($dataString) = @_;
2436 :     # Substitute the codes.
2437 :     $dataString =~ s!\[(/?[bi])\]!<$1>!g;
2438 :     $dataString =~ s!\[p\]!</p><p>!g;
2439 :     # Return the result.
2440 :     return $dataString;
2441 :     }
2442 :    
2443 :     =head2 Data Generation Utilities
2444 :    
2445 :     =head3 IntGen
2446 :    
2447 :     C<< my $integer = IntGen($min, $max); >>
2448 :    
2449 :     Returns a random number between the specified minimum and maximum (inclusive).
2450 :    
2451 :     =over 4
2452 :    
2453 :     =item min
2454 :    
2455 :     Minimum permissible return value.
2456 :    
2457 :     =item max
2458 :    
2459 :     Maximum permissible return value.
2460 :    
2461 :     =item RETURN
2462 :    
2463 :     Returns a value no lower than the minimum and no greater than the maximum.
2464 :    
2465 :     =back
2466 :    
2467 :     =cut
2468 :    
2469 :     sub IntGen {
2470 :     # Get the parameters.
2471 :     my ($min, $max) = @_;
2472 :     # Determine the range of possible values. Note we put some space well above the
2473 :     # maximum value to give it a fighting chance of apppearing in the list.
2474 :     my $span = $max + 0.99 - $min;
2475 :     # Create an integer in the range.
2476 :     my $retVal = $min + int(rand($span));
2477 :     # Return the result.
2478 :     return $retVal;
2479 :     }
2480 :    
2481 :     =head3 RandChar
2482 :    
2483 :     C<< my $char = RandChar($sourceString); >>
2484 :    
2485 :     Select a random character from a string.
2486 :    
2487 :     =over 4
2488 :    
2489 :     =item sourceString
2490 :    
2491 :     String from which the random character should be selected.
2492 :    
2493 :     =item RETURN
2494 :    
2495 :     Returns a single character from the incoming string.
2496 :    
2497 :     =back
2498 :    
2499 :     =cut
2500 :    
2501 :     sub RandChar {
2502 :     # Get the parameter.
2503 :     my ($sourceString) = @_;
2504 :     # Select a random character.
2505 :     my $retVal = IntGen(0, (length $sourceString) - 1);
2506 :     # Return it.
2507 :     return substr($sourceString, $retVal, 1);
2508 :     }
2509 :    
2510 :     =head3 RandChars
2511 :    
2512 :     C<< my $string = RandChars($sourceString, $length); >>
2513 :    
2514 :     Create a string from characters taken from a source string.
2515 :    
2516 :     =over 4
2517 :    
2518 :     =item sourceString
2519 :    
2520 :     String from which the random characters should be selected.
2521 :    
2522 :     =item length
2523 :    
2524 :     Number of characters to put in the output string.
2525 :    
2526 :     =item RETURN
2527 :    
2528 :     Returns a string of the specified length consisting of characters taken from the
2529 :     source string.
2530 :    
2531 :     =back
2532 :    
2533 :     =cut
2534 :    
2535 :     sub RandChars {
2536 :     # Get the parameters.
2537 :     my ($sourceString, $length) = @_;
2538 :     # Call RandChar repeatedly to generate the string.
2539 :     my $retVal = "";
2540 :     for (my $i = 0; $i < $length; $i++) {
2541 :     $retVal .= RandChar($sourceString);
2542 :     }
2543 :     # Return the result.
2544 :     return $retVal;
2545 :     }
2546 :    
2547 :     =head3 RandParam
2548 :    
2549 :     C<< my $value = RandParam($parm1, $parm2, ... $parmN); >>
2550 :    
2551 :     Return a randomly-selected value from the parameter list.
2552 :    
2553 :     =over 4
2554 :    
2555 :     =item parm1, parm2, ... parmN
2556 :    
2557 :     List of values of which one will be selected.
2558 :    
2559 :     =item RETURN
2560 :    
2561 :     Returns a randomly-chosen value from the specified list.
2562 :    
2563 :     =back
2564 :    
2565 :     =cut
2566 :    
2567 :     sub RandParam {
2568 :     # Get the parameter.
2569 :     my @parms = @_;
2570 :     # Choose a random parameter from the list.
2571 :     my $chosenIndex = IntGen(0, $#parms);
2572 :     return $parms[$chosenIndex];
2573 :     }
2574 :    
2575 :     =head3 StringGen
2576 :    
2577 :     C<< my $string = StringGen($pattern1, $pattern2, ... $patternN); >>
2578 :    
2579 :     Returns a random string derived from a randomly-chosen format pattern. The pattern
2580 :     can either be a number (indicating the number of characters desired, or the letter
2581 :     C<P> followed by a picture. The picture should contain C<A> when a letter is desired,
2582 :     C<9> when a digit is desired, C<V> when a vowel is desired, C<K> when a consonant is
2583 :     desired, and C<X> when a letter or a digit is desired. Any other character will be
2584 :     translated as a literal.
2585 :    
2586 :     =over 4
2587 :    
2588 :     =item pattern1, pattern2, ... patternN
2589 :    
2590 :     List of patterns to be used to generate string values.
2591 :    
2592 :     =item RETURN
2593 :    
2594 :     A single string generated from a pattern.
2595 :    
2596 :     =back
2597 :    
2598 :     =cut
2599 :    
2600 :     sub StringGen {
2601 :     # Get the parameters.
2602 :     my @patterns = @_;
2603 :     # Choose the appropriate pattern.
2604 :     my $chosenPattern = RandParam(@patterns);
2605 :     # Declare the return variable.
2606 :     my $retVal = "";
2607 :     # Determine whether this is a count or a picture pattern.
2608 :     if ($chosenPattern =~ m/^\d+/) {
2609 :     # Here we have a count. Get the string of source characters.
2610 :     my $letterString = $PictureTable{'X'};
2611 :     my $stringLen = length $letterString;
2612 :     # Save the number of characters we have to generate.
2613 :     my $charsLeft = $chosenPattern;
2614 :     # Loop until the return variable is full.
2615 :     while ($charsLeft > 0) {
2616 :     # Generate a random position in the soruce string.
2617 :     my $stringIndex = IntGen(0, $stringLen - 1);
2618 :     # Compute the number of characters to pull out of the source string.
2619 :     my $chunkSize = $stringLen - $stringIndex;
2620 :     if ($chunkSize > $charsLeft) { $chunkSize = $charsLeft; }
2621 :     # Stuff this chunk into the return value.
2622 :     $retVal .= substr($letterString, $stringIndex, $chunkSize);
2623 :     # Record the data moved.
2624 :     $charsLeft -= $chunkSize;
2625 :     }
2626 :     } elsif ($chosenPattern =~ m/^P/) {
2627 :     # Here we have a picture string. We will move through the picture one
2628 :     # character at a time generating data.
2629 :     for (my $i = 1; $i < length $chosenPattern; $i++) {
2630 :     # Get this picture character.
2631 :     my $chr = substr($chosenPattern, $i, 1);
2632 :     # Check to see if the picture char is one we recognize.
2633 :     if (exists $PictureTable{$chr}) {
2634 :     # Choose a random character from the available values for this
2635 :     # picture character.
2636 :     $retVal .= RandChar($PictureTable{$chr});
2637 :     } else {
2638 :     # Copy in the picture character as a literal.
2639 :     $retVal .= $chr;
2640 :     }
2641 :     }
2642 :     } else {
2643 :     # Here we have neither a picture string or a letter count, so we treat
2644 :     # the string as a literal.
2645 :     $retVal = $chosenPattern;
2646 :     }
2647 :     # Return the string formed.
2648 :     return $retVal;
2649 :     }
2650 :    
2651 :     =head3 DateGen
2652 :    
2653 :     C<< my $date = DateGen($startDayOffset, $endDayOffset, $minutes); >>
2654 :    
2655 :     Return a numeric timestamp within the specified range of days with the specified minute
2656 :     value. The range of days is specified relevant to the current day. Thus, the call
2657 :    
2658 :     C<< my $date = DateGen(-1, 5, 720); >>
2659 :    
2660 :     will return a timestamp at noon (72 minutes past midnight) sometime during the week that
2661 :     began on the preceding day. If you want a random minute of the day, simply combine with
2662 :     a call to L</IntGen>, as follows.
2663 :    
2664 :     C<< my $date = DateGen(-1, 5, IntGen(0, 1439)); >>
2665 :    
2666 :     =over 4
2667 :    
2668 :     =item startDayOffset
2669 :    
2670 :     The earliest day that can be returned, relative to the current day.
2671 :    
2672 :     =item endDayOffset
2673 :    
2674 :     The latest day that can be returned, related to the current day.
2675 :    
2676 :     =item minutes
2677 :    
2678 :     Number of minutes into the selected day that should be used.
2679 :    
2680 :     =back
2681 :    
2682 :     =cut
2683 :    
2684 :     sub DateGen {
2685 :     # Get the parameters.
2686 :     my ($startDayOffset, $endDayOffset, $minutes) = @_;
2687 :     # Get midnight of the current day.
2688 :     my $now = time();
2689 :     my ($sec, $min, $hour) = localtime($now);
2690 :     my $today = $now - (($hour * 60 + $min) * 60 + $sec);
2691 :     # Compute the day we want.
2692 :     my $newDay = IntGen($startDayOffset, $endDayOffset) * 86400 + $today;
2693 :     # Add the minutes.
2694 :     my $retVal = $newDay + $minutes * 60;
2695 :     # Return the result.
2696 :     return $retVal;
2697 :     }
2698 :    
2699 :     =head3 FloatGen
2700 :    
2701 :     C<< my $number = FloatGen($min, $max); >>
2702 :    
2703 :     Return a random floating-point number greater than or equal to the specified minimum and
2704 :     less than the specified maximum.
2705 :    
2706 :     =over 4
2707 :    
2708 :     =item min
2709 :    
2710 :     Minimum permissible value for the number returned.
2711 :    
2712 :     =item max
2713 :    
2714 :     Maximum permissible value for the number returned.
2715 :    
2716 :     =item RETURN
2717 :    
2718 :     Returns a floating-point number anywhere in the specified range.
2719 :    
2720 :     =back
2721 :    
2722 :     =cut
2723 :    
2724 :     sub FloatGen {
2725 :     # Get the parameters.
2726 :     my ($min, $max) = @_;
2727 :     # Generate the result.
2728 :     my $retVal = rand($max - $min) + $min;
2729 :     return $retVal;
2730 :     }
2731 :    
2732 :     =head3 ListGen
2733 :    
2734 :     C<< my @list = ListGen($pattern, $count); >>
2735 :    
2736 :     Return a list containing a fixed number of randomly-generated strings.
2737 :    
2738 :     =over 4
2739 :    
2740 :     =item pattern
2741 :    
2742 :     A pattern (in the form expected by L</StringGen>) that should be used to generate the
2743 :     strings in the list.
2744 :    
2745 :     =item count
2746 :    
2747 :     The number of list entries to generate.
2748 :    
2749 :     =item RETURN
2750 :    
2751 :     Returns a list consisting of the specified number of strings.
2752 :    
2753 :     =back
2754 :    
2755 :     =cut
2756 :    
2757 :     sub ListGen {
2758 :     # Get the parameters.
2759 :     my ($pattern, $count) = @_;
2760 :     # Generate the list.
2761 :     my @retVal = ();
2762 :     for (my $i = 0; $i < $count; $i++) {
2763 :     push @retVal, StringGen($pattern);
2764 :     }
2765 :     # Return it.
2766 :     return @retVal;
2767 :     }
2768 :    
2769 :     1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3