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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3