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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3