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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3