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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3