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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3