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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3