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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.22 - (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 : parrello 1.22 # Get the input file size.
1331 :     my $fileSize = -s $fileName;
1332 : parrello 1.10 # Get the relation data.
1333 :     my $relation = $self->_FindRelation($relationName);
1334 :     # Check the truncation flag.
1335 :     if ($truncateFlag) {
1336 :     Trace("Creating table $relationName") if T(2);
1337 : parrello 1.19 # Compute the row count estimate. We take the size of the load file,
1338 :     # divide it by the estimated row size, and then multiply by 1.5 to
1339 :     # leave extra room. We postulate a minimum row count of 1000 to
1340 :     # prevent problems with incoming empty load files.
1341 :     my $rowSize = $self->EstimateRowSize($relationName);
1342 :     my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1343 : parrello 1.10 # Re-create the table without its index.
1344 : parrello 1.19 $self->CreateTable($relationName, 0, $estimate);
1345 : parrello 1.10 # If this is a pre-index DBMS, create the index here.
1346 :     if ($dbh->{_preIndex}) {
1347 :     eval {
1348 :     $self->CreateIndex($relationName);
1349 :     };
1350 :     if ($@) {
1351 :     $retVal->AddMessage($@);
1352 :     }
1353 :     }
1354 :     }
1355 : parrello 1.3 # Load the table.
1356 : parrello 1.10 my $rv;
1357 :     eval {
1358 : parrello 1.20 $rv = $dbh->load_table(file => $fileName, tbl => $relationName);
1359 : parrello 1.10 };
1360 :     if (!defined $rv) {
1361 : parrello 1.3 $retVal->AddMessage($@) if ($@);
1362 : parrello 1.20 $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1363 : parrello 1.10 Trace("Table load failed for $relationName.") if T(1);
1364 :     } else {
1365 : parrello 1.22 # Here we successfully loaded the table.
1366 :     $retVal->Add("tables");
1367 :     my $size = -s $fileName;
1368 :     Trace("$size bytes loaded into $relationName.") if T(2);
1369 : parrello 1.10 # If we're rebuilding, we need to create the table indexes.
1370 :     if ($truncateFlag && ! $dbh->{_preIndex}) {
1371 :     eval {
1372 :     $self->CreateIndex($relationName);
1373 :     };
1374 :     if ($@) {
1375 :     $retVal->AddMessage($@);
1376 :     }
1377 :     }
1378 :     }
1379 :     # Commit the database changes.
1380 :     $dbh->commit_tran;
1381 : parrello 1.20 # Analyze the table to improve performance.
1382 : olson 1.16 $dbh->vacuum_it($relationName);
1383 : parrello 1.10 # Return the statistics.
1384 :     return $retVal;
1385 : parrello 1.1 }
1386 :    
1387 :     =head3 GenerateEntity
1388 :    
1389 : parrello 1.18 C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>
1390 : parrello 1.1
1391 :     Generate the data for a new entity instance. This method creates a field hash suitable for
1392 :     passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest
1393 :     of the fields are generated using information in the database schema.
1394 :    
1395 :     Each data type has a default algorithm for generating random test data. This can be overridden
1396 :     by including a B<DataGen> element in the field. If this happens, the content of the element is
1397 :     executed as a PERL program in the context of this module. The element may make use of a C<$this>
1398 :     variable which contains the field hash as it has been built up to the current point. If any
1399 :     fields are dependent on other fields, the C<pass> attribute can be used to control the order
1400 :     in which the fields are generated. A field with a high data pass number will be generated after
1401 :     a field with a lower one. If any external values are needed, they should be passed in via the
1402 :     optional third parameter, which will be available to the data generation script under the name
1403 :     C<$value>. Several useful utility methods are provided for generating random values, including
1404 :     L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated
1405 :     in the form of a timestamp number rather than a string.
1406 :    
1407 :     =over 4
1408 :    
1409 :     =item id
1410 :    
1411 :     ID to assign to the new entity.
1412 :    
1413 :     =item type
1414 :    
1415 :     Type name for the new entity.
1416 :    
1417 :     =item values
1418 :    
1419 :     Hash containing additional values that might be needed by the data generation methods (optional).
1420 :    
1421 :     =back
1422 :    
1423 :     =cut
1424 :    
1425 :     sub GenerateEntity {
1426 : parrello 1.10 # Get the parameters.
1427 :     my ($self, $id, $type, $values) = @_;
1428 :     # Create the return hash.
1429 :     my $this = { id => $id };
1430 :     # Get the metadata structure.
1431 :     my $metadata = $self->{_metaData};
1432 :     # Get this entity's list of fields.
1433 :     if (!exists $metadata->{Entities}->{$type}) {
1434 :     Confess("Unrecognized entity type $type in GenerateEntity.");
1435 :     } else {
1436 :     my $entity = $metadata->{Entities}->{$type};
1437 :     my $fields = $entity->{Fields};
1438 :     # Generate data from the fields.
1439 :     _GenerateFields($this, $fields, $type, $values);
1440 :     }
1441 :     # Return the hash created.
1442 :     return $this;
1443 : parrello 1.1 }
1444 :    
1445 : parrello 1.6 =head3 GetEntity
1446 :    
1447 : parrello 1.18 C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>
1448 : parrello 1.6
1449 :     Return an object describing the entity instance with a specified ID.
1450 :    
1451 :     =over 4
1452 :    
1453 :     =item entityType
1454 :    
1455 :     Entity type name.
1456 :    
1457 :     =item ID
1458 :    
1459 :     ID of the desired entity.
1460 :    
1461 :     =item RETURN
1462 :    
1463 :     Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
1464 :     instance is found with the specified key.
1465 :    
1466 :     =back
1467 :    
1468 :     =cut
1469 :    
1470 :     sub GetEntity {
1471 : parrello 1.10 # Get the parameters.
1472 :     my ($self, $entityType, $ID) = @_;
1473 :     # Create a query.
1474 :     my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID);
1475 :     # Get the first (and only) object.
1476 :     my $retVal = $query->Fetch();
1477 :     # Return the result.
1478 :     return $retVal;
1479 : parrello 1.6 }
1480 :    
1481 :     =head3 GetEntityValues
1482 :    
1483 : parrello 1.18 C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>
1484 : parrello 1.6
1485 :     Return a list of values from a specified entity instance.
1486 :    
1487 :     =over 4
1488 :    
1489 :     =item entityType
1490 :    
1491 :     Entity type name.
1492 :    
1493 :     =item ID
1494 :    
1495 :     ID of the desired entity.
1496 :    
1497 :     =item fields
1498 :    
1499 :     List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
1500 :    
1501 :     =item RETURN
1502 :    
1503 :     Returns a flattened list of the values of the specified fields for the specified entity.
1504 :    
1505 :     =back
1506 :    
1507 :     =cut
1508 :    
1509 :     sub GetEntityValues {
1510 : parrello 1.10 # Get the parameters.
1511 :     my ($self, $entityType, $ID, $fields) = @_;
1512 :     # Get the specified entity.
1513 :     my $entity = $self->GetEntity($entityType, $ID);
1514 :     # Declare the return list.
1515 :     my @retVal = ();
1516 :     # If we found the entity, push the values into the return list.
1517 :     if ($entity) {
1518 :     push @retVal, $entity->Values($fields);
1519 :     }
1520 :     # Return the result.
1521 :     return @retVal;
1522 : parrello 1.6 }
1523 : parrello 1.1
1524 : parrello 1.7 =head3 GetAll
1525 :    
1526 : parrello 1.18 C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
1527 : parrello 1.7
1528 :     Return a list of values taken from the objects returned by a query. The first three
1529 :     parameters correspond to the parameters of the L</Get> method. The final parameter is
1530 :     a list of the fields desired from each record found by the query. The field name
1531 :     syntax is the standard syntax used for fields in the B<ERDB> system--
1532 :     B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
1533 :     or relationship and I<fieldName> is the name of the field.
1534 :    
1535 :     The list returned will be a list of lists. Each element of the list will contain
1536 :     the values returned for the fields specified in the fourth parameter. If one of the
1537 :     fields specified returns multiple values, they are flattened in with the rest. For
1538 :     example, the following call will return a list of the features in a particular
1539 :     spreadsheet cell, and each feature will be represented by a list containing the
1540 :     feature ID followed by all of its aliases.
1541 :    
1542 : parrello 1.18 C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
1543 : parrello 1.7
1544 :     =over 4
1545 :    
1546 :     =item objectNames
1547 :    
1548 :     List containing the names of the entity and relationship objects to be retrieved.
1549 :    
1550 :     =item filterClause
1551 :    
1552 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1553 :     be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1554 :     B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1555 :     parameter list as additional parameters. The fields in a filter clause can come from primary
1556 :     entity relations, relationship relations, or secondary entity relations; however, all of the
1557 :     entities and relationships involved must be included in the list of object names.
1558 :    
1559 :     =item parameterList
1560 :    
1561 :     List of the parameters to be substituted in for the parameters marks in the filter clause.
1562 :    
1563 :     =item fields
1564 :    
1565 :     List of the fields to be returned in each element of the list returned.
1566 :    
1567 :     =item count
1568 :    
1569 :     Maximum number of records to return. If omitted or 0, all available records will be returned.
1570 :    
1571 :     =item RETURN
1572 :    
1573 :     Returns a list of list references. Each element of the return list contains the values for the
1574 :     fields specified in the B<fields> parameter.
1575 :    
1576 :     =back
1577 :    
1578 :     =cut
1579 :     #: Return Type @@;
1580 :     sub GetAll {
1581 : parrello 1.10 # Get the parameters.
1582 :     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
1583 :     # Translate the parameters from a list reference to a list. If the parameter
1584 :     # list is a scalar we convert it into a singleton list.
1585 :     my @parmList = ();
1586 :     if (ref $parameterList eq "ARRAY") {
1587 :     @parmList = @{$parameterList};
1588 :     } else {
1589 :     push @parmList, $parameterList;
1590 :     }
1591 :     # Create the query.
1592 :     my $query = $self->Get($objectNames, $filterClause, @parmList);
1593 :     # Set up a counter of the number of records read.
1594 :     my $fetched = 0;
1595 :     # Insure the counter has a value.
1596 :     if (!defined $count) {
1597 :     $count = 0;
1598 :     }
1599 :     # Loop through the records returned, extracting the fields. Note that if the
1600 :     # counter is non-zero, we stop when the number of records read hits the count.
1601 :     my @retVal = ();
1602 :     while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
1603 :     my @rowData = $row->Values($fields);
1604 :     push @retVal, \@rowData;
1605 :     $fetched++;
1606 :     }
1607 :     # Return the resulting list.
1608 :     return @retVal;
1609 : parrello 1.7 }
1610 :    
1611 : parrello 1.18 =head3 EstimateRowSize
1612 :    
1613 :     C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
1614 :    
1615 :     Estimate the row size of the specified relation. The estimated row size is computed by adding
1616 :     up the average length for each data type.
1617 :    
1618 :     =over 4
1619 :    
1620 :     =item relName
1621 :    
1622 :     Name of the relation whose estimated row size is desired.
1623 :    
1624 :     =item RETURN
1625 :    
1626 :     Returns an estimate of the row size for the specified relation.
1627 :    
1628 :     =back
1629 :    
1630 :     =cut
1631 :     #: Return Type $;
1632 :     sub EstimateRowSize {
1633 :     # Get the parameters.
1634 :     my ($self, $relName) = @_;
1635 :     # Declare the return variable.
1636 :     my $retVal = 0;
1637 :     # Find the relation descriptor.
1638 :     my $relation = $self->_FindRelation($relName);
1639 :     # Get the list of fields.
1640 :     for my $fieldData (@{$relation->{Fields}}) {
1641 :     # Get the field type and add its length.
1642 :     my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
1643 :     $retVal += $fieldLen;
1644 :     }
1645 :     # Return the result.
1646 :     return $retVal;
1647 :     }
1648 :    
1649 : parrello 1.1 =head2 Internal Utility Methods
1650 :    
1651 :     =head3 GetLoadStats
1652 :    
1653 :     Return a blank statistics object for use by the load methods.
1654 :    
1655 :     This is a static method.
1656 :    
1657 :     =cut
1658 :    
1659 :     sub _GetLoadStats {
1660 : parrello 1.10 return Stats->new('records');
1661 : parrello 1.1 }
1662 :    
1663 :     =head3 GenerateFields
1664 :    
1665 :     Generate field values from a field structure and store in a specified table. The field names
1666 :     are first sorted by pass count, certain pre-defined fields are removed from the list, and
1667 :     then we rip through them evaluation the data generation string. Fields in the primary relation
1668 :     are stored as scalars; fields in secondary relations are stored as value lists.
1669 :    
1670 :     This is a static method.
1671 :    
1672 :     =over 4
1673 :    
1674 :     =item this
1675 :    
1676 :     Hash table into which the field values should be placed.
1677 :    
1678 :     =item fields
1679 :    
1680 :     Field structure from which the field descriptors should be taken.
1681 :    
1682 :     =item type
1683 :    
1684 :     Type name of the object whose fields are being generated.
1685 :    
1686 :     =item values (optional)
1687 :    
1688 :     Reference to a value structure from which additional values can be taken.
1689 :    
1690 :     =item from (optiona)
1691 :    
1692 :     Reference to the source entity instance if relationship data is being generated.
1693 :    
1694 :     =item to (optional)
1695 :    
1696 :     Reference to the target entity instance if relationship data is being generated.
1697 :    
1698 :     =back
1699 :    
1700 :     =cut
1701 :    
1702 :     sub _GenerateFields {
1703 : parrello 1.10 # Get the parameters.
1704 :     my ($this, $fields, $type, $values, $from, $to) = @_;
1705 :     # Sort the field names by pass number.
1706 :     my @fieldNames = sort { $fields->{$a}->{DataGen}->{pass} <=> $fields->{$b}->{DataGen}->{pass} } keys %{$fields};
1707 :     # Loop through the field names, generating data.
1708 :     for my $name (@fieldNames) {
1709 :     # Only proceed if this field needs to be generated.
1710 :     if (!exists $this->{$name}) {
1711 :     # Get this field's data generation descriptor.
1712 :     my $fieldDescriptor = $fields->{$name};
1713 :     my $data = $fieldDescriptor->{DataGen};
1714 :     # Get the code to generate the field value.
1715 :     my $codeString = $data->{content};
1716 :     # Determine whether or not this field is in the primary relation.
1717 :     if ($fieldDescriptor->{relation} eq $type) {
1718 :     # Here we have a primary relation field. Store the field value as
1719 :     # a scalar.
1720 :     $this->{$name} = eval($codeString);
1721 :     } else {
1722 :     # Here we have a secondary relation field. Create a null list
1723 :     # and push the desired number of field values onto it.
1724 :     my @fieldValues = ();
1725 :     my $count = IntGen(0,$data->{testCount});
1726 :     for (my $i = 0; $i < $count; $i++) {
1727 :     my $newValue = eval($codeString);
1728 :     push @fieldValues, $newValue;
1729 :     }
1730 :     # Store the value list in the main hash.
1731 :     $this->{$name} = \@fieldValues;
1732 :     }
1733 :     }
1734 :     }
1735 : parrello 1.1 }
1736 :    
1737 :     =head3 DumpRelation
1738 :    
1739 :     Dump the specified relation's to the specified output file in tab-delimited format.
1740 :    
1741 :     This is an instance method.
1742 :    
1743 :     =over 4
1744 :    
1745 :     =item outputDirectory
1746 :    
1747 :     Directory to contain the output file.
1748 :    
1749 :     =item relationName
1750 :    
1751 :     Name of the relation to dump.
1752 :    
1753 :     =item relation
1754 :    
1755 :     Structure describing the relation to be dumped.
1756 :    
1757 :     =back
1758 :    
1759 :     =cut
1760 :    
1761 :     sub _DumpRelation {
1762 : parrello 1.10 # Get the parameters.
1763 :     my ($self, $outputDirectory, $relationName, $relation) = @_;
1764 :     # Open the output file.
1765 :     my $fileName = "$outputDirectory/$relationName.dtx";
1766 :     open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
1767 :     # Create a query for the specified relation.
1768 :     my $dbh = $self->{_dbh};
1769 :     my $query = $dbh->prepare_command("SELECT * FROM $relationName");
1770 :     # Execute the query.
1771 :     $query->execute() || Confess("SELECT error dumping $relationName.");
1772 :     # Loop through the results.
1773 :     while (my @row = $query->fetchrow) {
1774 :     # Escape any tabs or new-lines in the row text.
1775 :     for my $field (@row) {
1776 :     $field =~ s/\n/\\n/g;
1777 :     $field =~ s/\t/\\t/g;
1778 :     }
1779 :     # Tab-join the row and write it to the output file.
1780 :     my $rowText = join("\t", @row);
1781 :     print DTXOUT "$rowText\n";
1782 :     }
1783 :     # Close the output file.
1784 :     close DTXOUT;
1785 : parrello 1.1 }
1786 :    
1787 :     =head3 GetStructure
1788 :    
1789 :     Get the data structure for a specified entity or relationship.
1790 :    
1791 :     This is an instance method.
1792 :    
1793 :     =over 4
1794 :    
1795 :     =item objectName
1796 :    
1797 :     Name of the desired entity or relationship.
1798 :    
1799 :     =item RETURN
1800 :    
1801 :     The descriptor for the specified object.
1802 :    
1803 :     =back
1804 :    
1805 :     =cut
1806 :    
1807 :     sub _GetStructure {
1808 : parrello 1.10 # Get the parameters.
1809 :     my ($self, $objectName) = @_;
1810 :     # Get the metadata structure.
1811 :     my $metadata = $self->{_metaData};
1812 :     # Declare the variable to receive the descriptor.
1813 :     my $retVal;
1814 :     # Get the descriptor from the metadata.
1815 :     if (exists $metadata->{Entities}->{$objectName}) {
1816 :     $retVal = $metadata->{Entities}->{$objectName};
1817 :     } elsif (exists $metadata->{Relationships}->{$objectName}) {
1818 :     $retVal = $metadata->{Relationships}->{$objectName};
1819 :     } else {
1820 :     Confess("Object $objectName not found in database.");
1821 :     }
1822 :     # Return the descriptor.
1823 :     return $retVal;
1824 : parrello 1.1 }
1825 :    
1826 :     =head3 GetRelationTable
1827 :    
1828 :     Get the list of relations for a specified entity or relationship.
1829 :    
1830 :     This is an instance method.
1831 :    
1832 :     =over 4
1833 :    
1834 :     =item objectName
1835 :    
1836 :     Name of the desired entity or relationship.
1837 :    
1838 :     =item RETURN
1839 :    
1840 :     A table containing the relations for the specified object.
1841 :    
1842 :     =back
1843 :    
1844 :     =cut
1845 :    
1846 :     sub _GetRelationTable {
1847 : parrello 1.10 # Get the parameters.
1848 :     my ($self, $objectName) = @_;
1849 :     # Get the descriptor from the metadata.
1850 :     my $objectData = $self->_GetStructure($objectName);
1851 :     # Return the object's relation list.
1852 :     return $objectData->{Relations};
1853 : parrello 1.1 }
1854 :    
1855 :     =head3 GetFieldTable
1856 :    
1857 :     Get the field structure for a specified entity or relationship.
1858 :    
1859 :     This is an instance method.
1860 :    
1861 :     =over 4
1862 :    
1863 :     =item objectName
1864 :    
1865 :     Name of the desired entity or relationship.
1866 :    
1867 :     =item RETURN
1868 :    
1869 :     The table containing the field descriptors for the specified object.
1870 :    
1871 :     =back
1872 :    
1873 :     =cut
1874 :    
1875 :     sub _GetFieldTable {
1876 : parrello 1.10 # Get the parameters.
1877 :     my ($self, $objectName) = @_;
1878 :     # Get the descriptor from the metadata.
1879 :     my $objectData = $self->_GetStructure($objectName);
1880 :     # Return the object's field table.
1881 :     return $objectData->{Fields};
1882 : parrello 1.1 }
1883 :    
1884 :     =head3 ValidateFieldNames
1885 :    
1886 :     Determine whether or not the field names are valid. A description of the problems with the names
1887 :     will be written to the standard error output. If there is an error, this method will abort. This is
1888 :     a static method.
1889 :    
1890 :     =over 4
1891 :    
1892 :     =item metadata
1893 :    
1894 :     Metadata structure loaded from the XML data definition.
1895 :    
1896 :     =back
1897 :    
1898 :     =cut
1899 :    
1900 :     sub _ValidateFieldNames {
1901 : parrello 1.10 # Get the object.
1902 :     my ($metadata) = @_;
1903 :     # Declare the return value. We assume success.
1904 :     my $retVal = 1;
1905 :     # Loop through the sections of the database definition.
1906 :     for my $section ('Entities', 'Relationships') {
1907 :     # Loop through the objects in this section.
1908 :     for my $object (values %{$metadata->{$section}}) {
1909 :     # Loop through the object's fields.
1910 :     for my $fieldName (keys %{$object->{Fields}}) {
1911 :     # Now we make some initial validations.
1912 :     if ($fieldName =~ /--/) {
1913 :     # Here we have a doubled minus sign.
1914 :     print STDERR "Field name $fieldName has a doubled hyphen.\n";
1915 :     $retVal = 0;
1916 :     } elsif ($fieldName !~ /^[A-Za-z]/) {
1917 :     # Here the field name is missing the initial letter.
1918 :     print STDERR "Field name $fieldName does not begin with a letter.\n";
1919 :     $retVal = 0;
1920 :     } else {
1921 :     # Strip out the minus signs. Everything remaining must be a letter
1922 :     # or digit.
1923 :     my $strippedName = $fieldName;
1924 :     $strippedName =~ s/-//g;
1925 :     if ($strippedName !~ /^[A-Za-z0-9]+$/) {
1926 :     print STDERR "Field name $fieldName contains illegal characters.\n";
1927 :     $retVal = 0;
1928 :     }
1929 :     }
1930 :     }
1931 :     }
1932 :     }
1933 :     # If an error was found, fail.
1934 :     if ($retVal == 0) {
1935 :     Confess("Errors found in field names.");
1936 :     }
1937 : parrello 1.1 }
1938 :    
1939 :     =head3 LoadRelation
1940 :    
1941 :     Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk
1942 :     file with the same name as the relation exists in the specified directory.
1943 :    
1944 :     This is an instance method.
1945 :    
1946 :     =over 4
1947 :    
1948 :     =item dbh
1949 :    
1950 :     DBKernel object for accessing the database.
1951 :    
1952 :     =item directoryName
1953 :    
1954 :     Name of the directory containing the tab-delimited data files.
1955 :    
1956 :     =item relationName
1957 :    
1958 :     Name of the relation to load.
1959 :    
1960 :     =item rebuild
1961 :    
1962 :     TRUE if the table should be dropped and re-created before loading.
1963 :    
1964 :     =item RETURN
1965 :    
1966 :     Returns a statistical object describing the number of records read and a list of error messages.
1967 :    
1968 :     =back
1969 :    
1970 :     =cut
1971 :    
1972 :     sub _LoadRelation {
1973 : parrello 1.10 # Get the parameters.
1974 :     my ($self, $directoryName, $relationName, $rebuild) = @_;
1975 :     # Create the file name.
1976 :     my $fileName = "$directoryName/$relationName";
1977 :     # If the file doesn't exist, try adding the .dtx suffix.
1978 :     if (! -e $fileName) {
1979 :     $fileName .= ".dtx";
1980 :     if (! -e $fileName) {
1981 :     $fileName = "";
1982 :     }
1983 :     }
1984 :     # Create the return object.
1985 :     my $retVal = _GetLoadStats();
1986 :     # If a file exists to load the table, its name will be in $fileName. Otherwise, $fileName will
1987 :     # be a null string.
1988 :     if ($fileName ne "") {
1989 :     # Load the relation from the file.
1990 :     $retVal = $self->LoadTable($fileName, $relationName, $rebuild);
1991 :     } elsif ($rebuild) {
1992 :     # Here we are rebuilding, but no file exists, so we just re-create the table.
1993 :     $self->CreateTable($relationName, 1);
1994 :     }
1995 :     # Return the statistics from the load.
1996 :     return $retVal;
1997 : parrello 1.1 }
1998 :    
1999 :     =head3 LoadMetaData
2000 :    
2001 :     This method loads the data describing this database from an XML file into a metadata structure.
2002 :     The resulting structure is a set of nested hash tables containing all the information needed to
2003 :     load or use the database. The schema for the XML file is F<ERDatabase.xml>.
2004 :    
2005 :     This is a static method.
2006 :    
2007 :     =over 4
2008 :    
2009 :     =item filename
2010 :    
2011 :     Name of the file containing the database definition.
2012 :    
2013 :     =item RETURN
2014 :    
2015 :     Returns a structure describing the database.
2016 :    
2017 :     =back
2018 :    
2019 :     =cut
2020 :    
2021 :     sub _LoadMetaData {
2022 : parrello 1.10 # Get the parameters.
2023 :     my ($filename) = @_;
2024 : parrello 1.15 Trace("Reading Sprout DBD from $filename.") if T(2);
2025 : parrello 1.10 # Slurp the XML file into a variable. Extensive use of options is used to insure we
2026 :     # get the exact structure we want.
2027 :     my $metadata = XML::Simple::XMLin($filename,
2028 :     GroupTags => { Relationships => 'Relationship',
2029 :     Entities => 'Entity',
2030 :     Fields => 'Field',
2031 :     Indexes => 'Index',
2032 :     IndexFields => 'IndexField'},
2033 :     KeyAttr => { Relationship => 'name',
2034 :     Entity => 'name',
2035 :     Field => 'name'},
2036 :     ForceArray => ['Field', 'Index', 'IndexField'],
2037 :     ForceContent => 1,
2038 :     NormalizeSpace => 2
2039 :     );
2040 :     Trace("XML metadata loaded from file $filename.") if T(1);
2041 :     # Before we go any farther, we need to validate the field and object names. If an error is found,
2042 :     # the method below will fail.
2043 :     _ValidateFieldNames($metadata);
2044 :     # Next we need to create a hash table for finding relations. The entities and relationships are
2045 :     # implemented as one or more database relations.
2046 :     my %masterRelationTable = ();
2047 :     # Loop through the entities.
2048 :     my $entityList = $metadata->{Entities};
2049 :     for my $entityName (keys %{$entityList}) {
2050 :     my $entityStructure = $entityList->{$entityName};
2051 :     #
2052 : parrello 1.12 # The first step is to create all the entity's default values. For C<Field> elements,
2053 : parrello 1.10 # the relation name must be added where it is not specified. For relationships,
2054 :     # the B<from-link> and B<to-link> fields must be inserted, and for entities an B<id>
2055 :     # field must be added to each relation. Finally, each field will have a C<PrettySort> attribute
2056 :     # added that can be used to pull the implicit fields to the top when displaying the field
2057 :     # documentation. The PrettySort values are 1-based and indicate in which pass through a
2058 :     # relation's data the field should be displayed-- 1 for the first pass, 2 for the second,
2059 :     # and so on.
2060 :     #
2061 :     # Fix up this entity.
2062 :     _FixupFields($entityStructure, $entityName, 2, 3);
2063 :     # Add the ID field.
2064 :     _AddField($entityStructure, 'id', { type => $entityStructure->{keyType},
2065 :     relation => $entityName,
2066 :     Notes => { content => "Unique identifier for this \[b\]$entityName\[/b\]." },
2067 :     PrettySort => 1});
2068 :     #
2069 :     # The current field list enables us to quickly find the relation containing a particular field.
2070 :     # We also need a list that tells us the fields in each relation. We do this by creating a
2071 :     # Relations structure in the entity structure and collating the fields into it based on their
2072 :     # C<relation> property. There is one tricky bit, which is that every relation has to have the
2073 :     # C<id> field in it. Note also that the field list is put into a C<Fields> member of the
2074 :     # relation's structure so that it looks more like the entity and relationship structures.
2075 :     #
2076 :     # First we need to create the relations list.
2077 :     my $relationTable = { };
2078 :     # Loop through the fields. We use a list of field names to prevent a problem with
2079 :     # the hash table cursor losing its place during the loop.
2080 :     my $fieldList = $entityStructure->{Fields};
2081 :     my @fieldNames = keys %{$fieldList};
2082 :     for my $fieldName (@fieldNames) {
2083 :     my $fieldData = $fieldList->{$fieldName};
2084 :     # Get the current field's relation name.
2085 :     my $relationName = $fieldData->{relation};
2086 :     # Insure the relation exists.
2087 :     if (!exists $relationTable->{$relationName}) {
2088 :     $relationTable->{$relationName} = { Fields => { } };
2089 :     }
2090 :     # Add the field to the relation's field structure.
2091 :     $relationTable->{$relationName}->{Fields}->{$fieldName} = $fieldData;
2092 :     }
2093 :     # Now that we've organized all our fields by relation name we need to do some serious
2094 :     # housekeeping. We must add the C<id> field to every relation and convert each relation
2095 :     # to a list of fields. First, we need the ID field itself.
2096 :     my $idField = $fieldList->{id};
2097 :     # Loop through the relations.
2098 :     for my $relationName (keys %{$relationTable}) {
2099 :     my $relation = $relationTable->{$relationName};
2100 :     # Get the relation's field list.
2101 :     my $relationFieldList = $relation->{Fields};
2102 :     # Add the ID field to it. If the field's already there, it will not make any
2103 :     # difference.
2104 :     $relationFieldList->{id} = $idField;
2105 :     # Convert the field set from a hash into a list using the pretty-sort number.
2106 :     $relation->{Fields} = _ReOrderRelationTable($relationFieldList);
2107 :     # Add the relation to the master table.
2108 :     $masterRelationTable{$relationName} = $relation;
2109 :     }
2110 :     # The indexes come next. The primary relation will have a unique-keyed index based on the ID field.
2111 :     # The other relations must have at least one index that begins with the ID field. In addition, the
2112 :     # metadata may require alternate indexes. We do those alternate indexes first. To begin, we need to
2113 :     # get the entity's field list and index list.
2114 :     my $indexList = $entityStructure->{Indexes};
2115 :     # Loop through the indexes.
2116 :     for my $indexData (@{$indexList}) {
2117 :     # We need to find this index's fields. All of them should belong to the same relation.
2118 :     # The ID field is an exception, since it's in all relations.
2119 :     my $relationName = '0';
2120 :     for my $fieldDescriptor (@{$indexData->{IndexFields}}) {
2121 :     # Get this field's name.
2122 :     my $fieldName = $fieldDescriptor->{name};
2123 :     # Only proceed if it is NOT the ID field.
2124 :     if ($fieldName ne 'id') {
2125 :     # Find the relation containing the current index field.
2126 :     my $thisName = $fieldList->{$fieldName}->{relation};
2127 :     if ($relationName eq '0') {
2128 :     # Here we're looking at the first field, so we save its relation name.
2129 :     $relationName = $thisName;
2130 :     } elsif ($relationName ne $thisName) {
2131 :     # Here we have a field mismatch.
2132 :     Confess("Mixed index: field $fieldName does not belong to relation $relationName.");
2133 :     }
2134 :     }
2135 :     }
2136 :     # Now $relationName is the name of the relation that contains this index. Add the index structure
2137 :     # to the relation.
2138 :     push @{$relationTable->{$relationName}->{Indexes}}, $indexData;
2139 :     }
2140 :     # Now each index has been put in a relation. We need to add the primary index for the primary
2141 :     # relation.
2142 :     push @{$relationTable->{$entityName}->{Indexes}},
2143 :     { IndexFields => [ {name => 'id', order => 'ascending'} ], Unique => 'true',
2144 :     Notes => { content => "Primary index for $entityName." }
2145 :     };
2146 :     # The next step is to insure that each relation has at least one index that begins with the ID field.
2147 :     # After that, we convert each relation's index list to an index table. We first need to loop through
2148 :     # the relations.
2149 :     for my $relationName (keys %{$relationTable}) {
2150 :     my $relation = $relationTable->{$relationName};
2151 :     # Get the relation's index list.
2152 :     my $indexList = $relation->{Indexes};
2153 :     # Insure this relation has an ID index.
2154 :     my $found = 0;
2155 :     for my $index (@{$indexList}) {
2156 :     if ($index->{IndexFields}->[0]->{name} eq "id") {
2157 :     $found = 1;
2158 :     }
2159 :     }
2160 :     if ($found == 0) {
2161 :     push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
2162 :     }
2163 :     # Now we need to convert the relation's index list to an index table. We begin by creating
2164 :     # an empty table in the relation structure.
2165 :     $relation->{Indexes} = { };
2166 :     # Loop through the indexes.
2167 :     my $count = 0;
2168 :     for my $index (@{$indexList}) {
2169 :     # Add this index to the index table.
2170 :     _AddIndex("idx$relationName$count", $relation, $index);
2171 :     # Increment the counter so that the next index has a different name.
2172 :     $count++;
2173 :     }
2174 :     }
2175 :     # Finally, we add the relation structure to the entity.
2176 :     $entityStructure->{Relations} = $relationTable;
2177 :     }
2178 :     # Loop through the relationships. Relationships actually turn out to be much simpler than entities.
2179 :     # For one thing, there is only a single constituent relation.
2180 :     my $relationshipList = $metadata->{Relationships};
2181 :     for my $relationshipName (keys %{$relationshipList}) {
2182 :     my $relationshipStructure = $relationshipList->{$relationshipName};
2183 :     # Fix up this relationship.
2184 :     _FixupFields($relationshipStructure, $relationshipName, 2, 3);
2185 :     # Format a description for the FROM field.
2186 :     my $fromEntity = $relationshipStructure->{from};
2187 :     my $fromComment = "<b>id</b> of the source <b><a href=\"#$fromEntity\">$fromEntity</a></b>.";
2188 :     # Get the FROM entity's key type.
2189 :     my $fromType = $entityList->{$fromEntity}->{keyType};
2190 :     # Add the FROM field.
2191 :     _AddField($relationshipStructure, 'from-link', { type => $fromType,
2192 :     relation => $relationshipName,
2193 :     Notes => { content => $fromComment },
2194 :     PrettySort => 1});
2195 :     # Format a description for the TO field.
2196 :     my $toEntity = $relationshipStructure->{to};
2197 :     my $toComment = "<b>id</b> of the target <b><a href=\"#$toEntity\">$toEntity</a></b>.";
2198 :     # Get the TO entity's key type.
2199 :     my $toType = $entityList->{$toEntity}->{keyType};
2200 :     # Add the TO field.
2201 :     _AddField($relationshipStructure, 'to-link', { type=> $toType,
2202 :     relation => $relationshipName,
2203 :     Notes => { content => $toComment },
2204 :     PrettySort => 1});
2205 :     # Create an index-free relation from the fields.
2206 :     my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
2207 :     Indexes => { } };
2208 :     $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
2209 :     # Create the FROM and TO indexes.
2210 :     _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
2211 :     _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
2212 :     # Add the relation to the master table.
2213 :     $masterRelationTable{$relationshipName} = $thisRelation;
2214 :     }
2215 :     # Now store the master relation table in the metadata structure.
2216 :     $metadata->{RelationTable} = \%masterRelationTable;
2217 :     # Our final task is to create the join table. The join table is a hash that describes all
2218 :     # the join clauses for traveling through the relationships. The join clause is an equality
2219 :     # condition that can be put into a WHERE clause in order to join two objects. Two relationships
2220 :     # can be joined if they share an entity in common; and an entity can be joined to a relationship
2221 :     # if the entity is at either end of the relationship.
2222 :     my %joinTable = ();
2223 :     # Loop through the entities.
2224 :     for my $entityName (keys %{$entityList}) {
2225 :     # Build three lists of the relationships connected to this entity. One will be
2226 :     # for relationships from the entity, one for relationships to the entity, and
2227 :     # one for recursive relationships.
2228 :     my @fromList = ();
2229 :     my @toList = ();
2230 :     my @bothList = ();
2231 : parrello 1.21 Trace("Join table build for $entityName.") if T(metadata => 4);
2232 : parrello 1.10 for my $relationshipName (keys %{$relationshipList}) {
2233 :     my $relationship = $relationshipList->{$relationshipName};
2234 :     # Determine if this relationship has our entity in one of its link fields.
2235 :     my $fromEntity = $relationship->{from};
2236 :     my $toEntity = $relationship->{to};
2237 : parrello 1.17 Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(4);
2238 : parrello 1.10 if ($fromEntity eq $entityName) {
2239 :     if ($toEntity eq $entityName) {
2240 :     # Here the relationship is recursive.
2241 :     push @bothList, $relationshipName;
2242 : parrello 1.21 Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
2243 : parrello 1.10 } else {
2244 :     # Here the relationship comes from the entity.
2245 :     push @fromList, $relationshipName;
2246 : parrello 1.21 Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
2247 : parrello 1.10 }
2248 :     } elsif ($toEntity eq $entityName) {
2249 :     # Here the relationship goes to the entity.
2250 :     push @toList, $relationshipName;
2251 : parrello 1.21 Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
2252 : parrello 1.10 }
2253 :     }
2254 :     # Create the nonrecursive joins. Note that we build two hashes for running
2255 :     # through the nonrecursive relationships since we'll have an outer loop
2256 :     # and an inner loop, and we can't do two "each" iterations on the same
2257 :     # hash table at the same time.
2258 :     my %directRelationships = ( from => \@fromList, to => \@toList );
2259 :     my %otherRelationships = ( from => \@fromList, to => \@toList );
2260 :     for my $linkType (keys %directRelationships) {
2261 :     my $relationships = $directRelationships{$linkType};
2262 :     # Loop through all the relationships.
2263 :     for my $relationshipName (@{$relationships}) {
2264 :     # Create joins between the entity and this relationship.
2265 :     my $linkField = "$relationshipName.${linkType}_link";
2266 :     my $joinClause = "$entityName.id = $linkField";
2267 : parrello 1.21 Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4);
2268 : parrello 1.10 $joinTable{"$entityName/$relationshipName"} = $joinClause;
2269 :     $joinTable{"$relationshipName/$entityName"} = $joinClause;
2270 :     # Create joins between this relationship and the other relationships.
2271 :     for my $otherType (keys %otherRelationships) {
2272 :     my $otherships = $otherRelationships{$otherType};
2273 :     for my $otherName (@{$otherships}) {
2274 :     # Get the key for this join.
2275 :     my $joinKey = "$otherName/$relationshipName";
2276 :     # Check for a duplicate or a self-join.
2277 :     if (exists $joinTable{$joinKey}) {
2278 :     # Here we have a duplicate, which means that the join
2279 :     # path is ambiguous. We delete the join from the join
2280 :     # table to prevent it from being used.
2281 :     delete $joinTable{$joinKey};
2282 :     Trace("Deleting ambiguous join $joinKey.") if T(4);
2283 :     } elsif ($otherName ne $relationshipName) {
2284 :     # Here we have a valid join. Note that joins between a
2285 :     # relationship and itself are prohibited.
2286 :     my $relJoinClause = "$otherName.${otherType}_link = $linkField";
2287 :     $joinTable{$joinKey} = $relJoinClause;
2288 : parrello 1.21 Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
2289 : parrello 1.10 }
2290 :     }
2291 :     }
2292 :     # Create joins between this relationship and the recursive relationships.
2293 :     # We don't need to check for ambiguous joins here, because a recursive
2294 :     # relationship can only be ambiguous with another recursive relationship,
2295 :     # and the incoming relationship from the outer loop is never recursive.
2296 :     for my $otherName (@bothList) {
2297 : parrello 1.21 Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4);
2298 : parrello 1.10 # Join from the left.
2299 :     $joinTable{"$relationshipName/$otherName"} =
2300 :     "$linkField = $otherName.from_link";
2301 :     # Join from the right.
2302 :     $joinTable{"$otherName/$relationshipName"} =
2303 :     "$otherName.to_link = $linkField";
2304 :     }
2305 :     }
2306 :     }
2307 :     # Create entity joins for the recursive relationships. Unlike the non-recursive
2308 :     # joins, the direction makes a difference with the recursive joins. This can give
2309 :     # rise to situations where we can't create the path we want; however, it is always
2310 :     # possible to get the same effect using multiple queries.
2311 :     for my $relationshipName (@bothList) {
2312 : parrello 1.21 Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
2313 : parrello 1.10 # Join to the entity from each direction.
2314 :     $joinTable{"$entityName/$relationshipName"} =
2315 :     "$entityName.id = $relationshipName.from_link";
2316 :     $joinTable{"$relationshipName/$entityName"} =
2317 :     "$relationshipName.to_link = $entityName.id";
2318 :     }
2319 :     }
2320 :     # Add the join table to the structure.
2321 :     $metadata->{Joins} = \%joinTable;
2322 :     # Return the slurped and fixed-up structure.
2323 :     return $metadata;
2324 : parrello 1.1 }
2325 :    
2326 :     =head3 CreateRelationshipIndex
2327 :    
2328 :     Create an index for a relationship's relation.
2329 :    
2330 :     This is a static method.
2331 :    
2332 :     =over 4
2333 :    
2334 :     =item indexKey
2335 :    
2336 :     Type of index: either C<"From"> or C<"To">.
2337 :    
2338 :     =item relationshipName
2339 :    
2340 :     Name of the relationship.
2341 :    
2342 :     =item relationshipStructure
2343 :    
2344 :     Structure describing the relationship that the index will sort.
2345 :    
2346 :     =back
2347 :    
2348 :     =cut
2349 :    
2350 :     sub _CreateRelationshipIndex {
2351 : parrello 1.10 # Get the parameters.
2352 :     my ($indexKey, $relationshipName, $relationshipStructure) = @_;
2353 :     # Get the target relation.
2354 :     my $relationStructure = $relationshipStructure->{Relations}->{$relationshipName};
2355 :     # Create a descriptor for the link field that goes at the beginning of this index.
2356 :     my $firstField = { name => lcfirst $indexKey . '-link', order => 'ascending' };
2357 :     # Get the target index descriptor.
2358 :     my $newIndex = $relationshipStructure->{$indexKey . "Index"};
2359 :     # Add the first field to the index's field list. Due to the craziness of PERL, if the
2360 :     # index descriptor does not exist, it will be created automatically so we can add
2361 :     # the field to it.
2362 :     unshift @{$newIndex->{IndexFields}}, $firstField;
2363 : parrello 1.12 # If this is a one-to-many relationship, the "To" index is unique.
2364 :     if ($relationshipStructure->{arity} eq "1M" && $indexKey eq "To") {
2365 :     $newIndex->{Unique} = 'true';
2366 :     }
2367 : parrello 1.10 # Add the index to the relation.
2368 :     _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
2369 : parrello 1.1 }
2370 :    
2371 :     =head3 AddIndex
2372 :    
2373 :     Add an index to a relation structure.
2374 :    
2375 :     This is a static method.
2376 :    
2377 :     =over 4
2378 :    
2379 :     =item indexName
2380 :    
2381 :     Name to give to the new index.
2382 :    
2383 :     =item relationStructure
2384 :    
2385 :     Relation structure to which the new index should be added.
2386 :    
2387 :     =item newIndex
2388 :    
2389 :     New index to add.
2390 :    
2391 :     =back
2392 :    
2393 :     =cut
2394 :    
2395 :     sub _AddIndex {
2396 : parrello 1.10 # Get the parameters.
2397 :     my ($indexName, $relationStructure, $newIndex) = @_;
2398 :     # We want to re-do the index's field list. Instead of an object for each field,
2399 :     # we want a string consisting of the field name optionally followed by the token DESC.
2400 :     my @fieldList = ( );
2401 :     for my $field (@{$newIndex->{IndexFields}}) {
2402 :     # Create a string containing the field name.
2403 :     my $fieldString = $field->{name};
2404 :     # Add the ordering token if needed.
2405 :     if ($field->{order} eq "descending") {
2406 :     $fieldString .= " DESC";
2407 :     }
2408 :     # Push the result onto the field list.
2409 :     push @fieldList, $fieldString;
2410 :     }
2411 :     # Store the field list just created as the new index field list.
2412 :     $newIndex->{IndexFields} = \@fieldList;
2413 :     # Add the index to the relation's index list.
2414 :     $relationStructure->{Indexes}->{$indexName} = $newIndex;
2415 : parrello 1.1 }
2416 :    
2417 :     =head3 FixupFields
2418 :    
2419 :     This method fixes the field list for an entity or relationship. It will add the caller-specified
2420 :     relation name to fields that do not have a name and set the C<PrettySort> value as specified.
2421 :    
2422 :     This is a static method.
2423 :    
2424 :     =over 4
2425 :    
2426 :     =item structure
2427 :    
2428 :     Entity or relationship structure to be fixed up.
2429 :    
2430 :     =item defaultRelationName
2431 :    
2432 :     Default relation name to be added to the fields.
2433 :    
2434 :     =item prettySortValue
2435 :    
2436 :     C<PrettySort> value for the relation's normal fields.
2437 :    
2438 :     =item textPrettySortValue
2439 :    
2440 :     C<PrettySort> value for the relation's text fields. This value can be set to one greater than the
2441 :     normal pretty sort value so that text fields go at the end of each relation.
2442 :    
2443 :     =back
2444 :    
2445 :     =cut
2446 :    
2447 :     sub _FixupFields {
2448 : parrello 1.10 # Get the parameters.
2449 :     my ($structure, $defaultRelationName, $prettySortValue, $textPrettySortValue) = @_;
2450 :     # Insure the structure has a field list.
2451 :     if (!exists $structure->{Fields}) {
2452 :     # Here it doesn't, so we create a new one.
2453 :     $structure->{Fields} = { };
2454 :     } else {
2455 :     # Here we have a field list. Loop through its fields.
2456 :     my $fieldStructures = $structure->{Fields};
2457 :     for my $fieldName (keys %{$fieldStructures}) {
2458 : parrello 1.8 Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
2459 : parrello 1.10 my $fieldData = $fieldStructures->{$fieldName};
2460 :     # Get the field type.
2461 :     my $type = $fieldData->{type};
2462 :     # Plug in a relation name if it is needed.
2463 :     Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
2464 :     # Plug in a data generator if we need one.
2465 :     if (!exists $fieldData->{DataGen}) {
2466 :     # The data generator will use the default for the field's type.
2467 :     $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };
2468 :     }
2469 :     # Plug in the defaults for the optional data generation parameters.
2470 :     Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });
2471 :     # Add the PrettySortValue.
2472 :     $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
2473 :     }
2474 :     }
2475 : parrello 1.1 }
2476 :    
2477 :     =head3 FixName
2478 :    
2479 :     Fix the incoming field name so that it is a legal SQL column name.
2480 :    
2481 :     This is a static method.
2482 :    
2483 :     =over 4
2484 :    
2485 :     =item fieldName
2486 :    
2487 :     Field name to fix.
2488 :    
2489 :     =item RETURN
2490 :    
2491 :     Returns the fixed-up field name.
2492 :    
2493 :     =back
2494 :    
2495 :     =cut
2496 :    
2497 :     sub _FixName {
2498 : parrello 1.10 # Get the parameter.
2499 :     my ($fieldName) = @_;
2500 :     # Replace its minus signs with underscores.
2501 :     $fieldName =~ s/-/_/g;
2502 :     # Return the result.
2503 :     return $fieldName;
2504 : parrello 1.1 }
2505 :    
2506 :     =head3 FixNames
2507 :    
2508 :     Fix all the field names in a list.
2509 :    
2510 :     This is a static method.
2511 :    
2512 :     =over 4
2513 :    
2514 :     =item field1, field2, field3, ... fieldn
2515 :    
2516 :     List of field names to fix.
2517 :    
2518 :     =item RETURN
2519 :    
2520 :     Returns a list of fixed-up versions of the incoming field names.
2521 :    
2522 :     =back
2523 :    
2524 :     =cut
2525 :    
2526 :     sub _FixNames {
2527 : parrello 1.10 # Create the result list.
2528 :     my @result = ( );
2529 :     # Loop through the incoming parameters.
2530 :     for my $field (@_) {
2531 :     push @result, _FixName($field);
2532 :     }
2533 :     # Return the result.
2534 :     return @result;
2535 : parrello 1.1 }
2536 :    
2537 :     =head3 AddField
2538 :    
2539 :     Add a field to a field list.
2540 :    
2541 :     This is a static method.
2542 :    
2543 :     =over 4
2544 :    
2545 :     =item structure
2546 :    
2547 :     Structure (usually an entity or relationship) that is to contain the field.
2548 :    
2549 :     =item fieldName
2550 :    
2551 :     Name of the new field.
2552 :    
2553 :     =item fieldData
2554 :    
2555 :     Structure containing the data to put in the field.
2556 :    
2557 :     =back
2558 :    
2559 :     =cut
2560 :    
2561 :     sub _AddField {
2562 : parrello 1.10 # Get the parameters.
2563 :     my ($structure, $fieldName, $fieldData) = @_;
2564 :     # Create the field structure by copying the incoming data.
2565 :     my $fieldStructure = {%{$fieldData}};
2566 :     # Get a reference to the field list itself.
2567 :     my $fieldList = $structure->{Fields};
2568 :     # Add the field to the field list.
2569 :     $fieldList->{$fieldName} = $fieldStructure;
2570 : parrello 1.1 }
2571 :    
2572 :     =head3 ReOrderRelationTable
2573 :    
2574 :     This method will take a relation table and re-sort it according to the implicit ordering of the
2575 :     C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.
2576 :     This requires creating a new hash that contains the field name in the C<name> property but doesn't
2577 :     have the C<PrettySort> property, and then inserting that new hash into the field list.
2578 :    
2579 :     This is a static method.
2580 :    
2581 :     =over 4
2582 :    
2583 :     =item relationTable
2584 :    
2585 :     Relation hash to be reformatted into a list.
2586 :    
2587 :     =item RETURN
2588 :    
2589 :     A list of field hashes.
2590 :    
2591 :     =back
2592 :    
2593 :     =cut
2594 :    
2595 :     sub _ReOrderRelationTable {
2596 : parrello 1.10 # Get the parameters.
2597 :     my ($relationTable) = @_;
2598 :     # Create the return list.
2599 :     my @resultList;
2600 :     # Rather than copy all the fields in a single pass, we make multiple passes and only copy
2601 :     # fields whose PrettySort value matches the current pass number. This process continues
2602 :     # until we process all the fields in the relation.
2603 :     my $fieldsLeft = (values %{$relationTable});
2604 :     for (my $sortPass = 1; $fieldsLeft > 0; $sortPass++) {
2605 :     # Loop through the fields. Note that we lexically sort the fields. This makes field name
2606 :     # secondary to pretty-sort number in the final ordering.
2607 :     for my $fieldName (sort keys %{$relationTable}) {
2608 :     # Get this field's data.
2609 :     my $fieldData = $relationTable->{$fieldName};
2610 :     # Verify the sort pass.
2611 :     if ($fieldData->{PrettySort} == $sortPass) {
2612 :     # Here we're in the correct pass. Denote we've found a field.
2613 :     $fieldsLeft--;
2614 :     # The next step is to create the field structure. This done by copying all
2615 :     # of the field elements except PrettySort and adding the name.
2616 :     my %thisField;
2617 :     for my $property (keys %{$fieldData}) {
2618 :     if ($property ne 'PrettySort') {
2619 :     $thisField{$property} = $fieldData->{$property};
2620 :     }
2621 :     }
2622 :     $thisField{name} = $fieldName;
2623 :     # Now we add this field to the end of the result list.
2624 :     push @resultList, \%thisField;
2625 :     }
2626 :     }
2627 :     }
2628 :     # Return a reference to the result list.
2629 :     return \@resultList;
2630 : parrello 1.1
2631 :     }
2632 :    
2633 :     =head3 IsPrimary
2634 :    
2635 :     Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary
2636 :     if it has the same name as an entity or relationship.
2637 :    
2638 :     This is an instance method.
2639 :    
2640 :     =over 4
2641 :    
2642 :     =item relationName
2643 :    
2644 :     Name of the relevant relation.
2645 :    
2646 :     =item RETURN
2647 :    
2648 :     Returns TRUE for a primary relation, else FALSE.
2649 :    
2650 :     =back
2651 :    
2652 :     =cut
2653 :    
2654 :     sub _IsPrimary {
2655 : parrello 1.10 # Get the parameters.
2656 :     my ($self, $relationName) = @_;
2657 :     # Check for the relation in the entity table.
2658 :     my $entityTable = $self->{_metaData}->{Entities};
2659 :     my $retVal = exists $entityTable->{$relationName};
2660 :     if (! $retVal) {
2661 :     # Check for it in the relationship table.
2662 :     my $relationshipTable = $self->{_metaData}->{Relationships};
2663 :     $retVal = exists $relationshipTable->{$relationName};
2664 :     }
2665 :     # Return the determination indicator.
2666 :     return $retVal;
2667 : parrello 1.1 }
2668 :    
2669 :     =head3 FindRelation
2670 :    
2671 :     Return the descriptor for the specified relation.
2672 :    
2673 :     This is an instance method.
2674 :    
2675 :     =over 4
2676 :    
2677 :     =item relationName
2678 :    
2679 :     Name of the relation whose descriptor is to be returned.
2680 :    
2681 :     =item RETURN
2682 :    
2683 :     Returns the object that describes the relation's indexes and fields.
2684 :    
2685 :     =back
2686 :    
2687 :     =cut
2688 :     sub _FindRelation {
2689 : parrello 1.10 # Get the parameters.
2690 :     my ($self, $relationName) = @_;
2691 :     # Get the relation's structure from the master relation table in the metadata structure.
2692 :     my $metaData = $self->{_metaData};
2693 :     my $retVal = $metaData->{RelationTable}->{$relationName};
2694 :     # Return it to the caller.
2695 :     return $retVal;
2696 : parrello 1.1 }
2697 :    
2698 :     =head2 HTML Documentation Utility Methods
2699 :    
2700 :     =head3 ComputeRelationshipSentence
2701 :    
2702 :     The relationship sentence consists of the relationship name between the names of the
2703 :     two related entities and an arity indicator.
2704 :    
2705 :     This is a static method.
2706 :    
2707 :     =over 4
2708 :    
2709 :     =item relationshipName
2710 :    
2711 :     Name of the relationship.
2712 :    
2713 :     =item relationshipStructure
2714 :    
2715 :     Relationship structure containing the relationship's description and properties.
2716 :    
2717 :     =item RETURN
2718 :    
2719 :     Returns a string containing the entity names on either side of the relationship name and an
2720 :     indicator of the arity.
2721 :    
2722 :     =back
2723 :    
2724 :     =cut
2725 :    
2726 :     sub _ComputeRelationshipSentence {
2727 : parrello 1.10 # Get the parameters.
2728 :     my ($relationshipName, $relationshipStructure) = @_;
2729 :     # Format the relationship sentence.
2730 :     my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";
2731 :     # Compute the arity.
2732 :     my $arityCode = $relationshipStructure->{arity};
2733 :     my $arity = $ArityTable{$arityCode};
2734 :     $result .= " ($arity)";
2735 :     return $result;
2736 : parrello 1.1 }
2737 :    
2738 :     =head3 ComputeRelationshipHeading
2739 :    
2740 :     The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
2741 :     names hyperlinked to the appropriate entity sections of the document.
2742 :    
2743 :     This is a static method.
2744 :    
2745 :     =over 4
2746 :    
2747 :     =item relationshipName
2748 :    
2749 :     Name of the relationship.
2750 :    
2751 :     =item relationshipStructure
2752 :    
2753 :     Relationship structure containing the relationship's description and properties.
2754 :    
2755 :     =item RETURN
2756 :    
2757 :     Returns a string containing the entity names on either side of the relationship name with the entity
2758 :     names hyperlinked.
2759 :    
2760 :     =back
2761 :    
2762 :     =cut
2763 :    
2764 :     sub _ComputeRelationshipHeading {
2765 : parrello 1.10 # Get the parameters.
2766 :     my ($relationshipName, $relationshipStructure) = @_;
2767 :     # Get the FROM and TO entity names.
2768 :     my $fromEntity = $relationshipStructure->{from};
2769 :     my $toEntity = $relationshipStructure->{to};
2770 :     # Format a relationship sentence with hyperlinks in it.
2771 :     my $result = "<a href=\"#$fromEntity\">$fromEntity</a> $relationshipName <a href=\"#$toEntity\">$toEntity</a>";
2772 :     return $result;
2773 : parrello 1.1 }
2774 :    
2775 :     =head3 ShowRelationTable
2776 :    
2777 :     Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
2778 :     table with three columns-- the field name, the field type, and the field description.
2779 :    
2780 :     This is a static method.
2781 :    
2782 :     =over 4
2783 :    
2784 :     =item relationName
2785 :    
2786 :     Name of the relation being formatted.
2787 :    
2788 :     =item relationData
2789 :    
2790 :     Hash containing the relation's fields and indexes.
2791 :    
2792 :     =item RETURN
2793 :    
2794 :     Returns an HTML string that can be used to display the relation name and all of its fields.
2795 :    
2796 :     =back
2797 :    
2798 :     =cut
2799 :    
2800 :     sub _ShowRelationTable {
2801 : parrello 1.10 # Get the parameters.
2802 :     my ($relationName, $relationData) = @_;
2803 :     # Start the relation's field table.
2804 :     my $htmlString = _OpenFieldTable($relationName);
2805 :     # Loop through the fields.
2806 :     for my $field (@{$relationData->{Fields}}) {
2807 :     $htmlString .= _ShowField($field);
2808 :     }
2809 :     # Close this relation's field table.
2810 :     $htmlString .= &_CloseTable;
2811 :     # Now we show the relation's indexes.
2812 :     $htmlString .= "<ul>\n";
2813 :     my $indexTable = $relationData->{Indexes};
2814 :     for my $indexName (sort keys %{$indexTable}) {
2815 :     my $indexData = $indexTable->{$indexName};
2816 :     # Determine whether or not the index is unique.
2817 :     my $fullName = $indexName;
2818 :     if (exists $indexData->{Unique} && $indexData->{Unique} eq "true") {
2819 :     $fullName .= " (unique)";
2820 :     }
2821 :     # Start an HTML list item for this index.
2822 :     $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
2823 :     # Add any note text.
2824 :     if (my $note = $indexData->{Notes}) {
2825 :     $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";
2826 :     }
2827 :     # Add the fiield list.
2828 :     $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
2829 :     # Close this entry.
2830 :     $htmlString .= "</ul></li>\n";
2831 :     }
2832 :     # Close off the index list.
2833 :     $htmlString .= "</ul>\n";
2834 : parrello 1.1 }
2835 :    
2836 :     =head3 OpenFieldTable
2837 :    
2838 :     This method creates the header string for the field table generated by L</ShowMetaData>.
2839 :    
2840 :     This is a static method.
2841 :    
2842 :     =over 4
2843 :    
2844 :     =item tablename
2845 :    
2846 :     Name of the table whose fields will be displayed.
2847 :    
2848 :     =item RETURN
2849 :    
2850 :     Returns a string containing the HTML for a field table's header.
2851 :    
2852 :     =back
2853 :    
2854 :     =cut
2855 :    
2856 :     sub _OpenFieldTable {
2857 : parrello 1.10 my ($tablename) = @_;
2858 :     return _OpenTable($tablename, 'Field', 'Type', 'Description');
2859 : parrello 1.1 }
2860 :    
2861 :     =head3 OpenTable
2862 :    
2863 :     This method creates the header string for an HTML table.
2864 :    
2865 :     This is a static method.
2866 :    
2867 :     =over 4
2868 :    
2869 :     =item tablename
2870 :    
2871 :     Title of the table.
2872 :    
2873 :     =item colName1, colName2, ..., colNameN
2874 :    
2875 :     List of column names.
2876 :    
2877 :     =item RETURN
2878 :    
2879 :     Returns a string containing the HTML for the desired table's header.
2880 :    
2881 :     =back
2882 :    
2883 :     =cut
2884 :    
2885 :     sub _OpenTable {
2886 : parrello 1.10 # Get the parameters.
2887 :     my ($tablename, @colNames) = @_;
2888 :     # Compute the number of columns.
2889 :     my $colCount = @colNames;
2890 :     # Generate the title row.
2891 :     my $htmlString = "<p><table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";
2892 :     # Loop through the columns, adding the column header rows.
2893 :     $htmlString .= "<tr>";
2894 :     for my $colName (@colNames) {
2895 :     $htmlString .= "<th>$colName</th>";
2896 :     }
2897 :     $htmlString .= "</tr>\n";
2898 :     return $htmlString;
2899 : parrello 1.1 }
2900 :    
2901 :     =head3 CloseTable
2902 :    
2903 :     This method returns the HTML for closing a table.
2904 :    
2905 :     This is a static method.
2906 :    
2907 :     =cut
2908 :    
2909 :     sub _CloseTable {
2910 : parrello 1.10 return "</table></p>\n";
2911 : parrello 1.1 }
2912 :    
2913 :     =head3 ShowField
2914 :    
2915 :     This method returns the HTML for displaying a row of field information in a field table.
2916 :    
2917 :     This is a static method.
2918 :    
2919 :     =over 4
2920 :    
2921 :     =item fieldData
2922 :    
2923 :     Table of data about the field.
2924 :    
2925 :     =item RETURN
2926 :    
2927 :     Returns an HTML string for a table row that shows the field's name, type, and description.
2928 :    
2929 :     =back
2930 :    
2931 :     =cut
2932 :    
2933 :     sub _ShowField {
2934 : parrello 1.10 # Get the parameters.
2935 :     my ($fieldData) = @_;
2936 :     # Create the HTML string.
2937 :     my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";
2938 :     # If we have content, add it as a third column.
2939 :     if (exists $fieldData->{Notes}) {
2940 :     $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";
2941 :     }
2942 :     # Close off the row.
2943 :     $htmlString .= "</tr>\n";
2944 :     # Return the result.
2945 :     return $htmlString;
2946 : parrello 1.1 }
2947 :    
2948 :     =head3 HTMLNote
2949 :    
2950 :     Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
2951 :     supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
2952 :     Except for C<[p]>, all the codes are closed by slash-codes. So, for
2953 :     example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
2954 :    
2955 :     This is a static method.
2956 :    
2957 :     =over 4
2958 :    
2959 :     =item dataString
2960 :    
2961 :     String to convert to HTML.
2962 :    
2963 :     =item RETURN
2964 :    
2965 :     An HTML string derived from the input string.
2966 :    
2967 :     =back
2968 :    
2969 :     =cut
2970 :    
2971 :     sub _HTMLNote {
2972 : parrello 1.10 # Get the parameter.
2973 :     my ($dataString) = @_;
2974 :     # Substitute the codes.
2975 :     $dataString =~ s!\[(/?[bi])\]!<$1>!g;
2976 :     $dataString =~ s!\[p\]!</p><p>!g;
2977 :     # Return the result.
2978 :     return $dataString;
2979 : parrello 1.1 }
2980 :    
2981 :     =head2 Data Generation Utilities
2982 :    
2983 :     =head3 IntGen
2984 :    
2985 :     C<< my $integer = IntGen($min, $max); >>
2986 :    
2987 :     Returns a random number between the specified minimum and maximum (inclusive).
2988 :    
2989 :     =over 4
2990 :    
2991 :     =item min
2992 :    
2993 :     Minimum permissible return value.
2994 :    
2995 :     =item max
2996 :    
2997 :     Maximum permissible return value.
2998 :    
2999 :     =item RETURN
3000 :    
3001 :     Returns a value no lower than the minimum and no greater than the maximum.
3002 :    
3003 :     =back
3004 :    
3005 :     =cut
3006 :    
3007 :     sub IntGen {
3008 : parrello 1.10 # Get the parameters.
3009 :     my ($min, $max) = @_;
3010 :     # Determine the range of possible values. Note we put some space well above the
3011 :     # maximum value to give it a fighting chance of apppearing in the list.
3012 :     my $span = $max + 0.99 - $min;
3013 :     # Create an integer in the range.
3014 :     my $retVal = $min + int(rand($span));
3015 :     # Return the result.
3016 :     return $retVal;
3017 : parrello 1.1 }
3018 :    
3019 :     =head3 RandChar
3020 :    
3021 :     C<< my $char = RandChar($sourceString); >>
3022 :    
3023 :     Select a random character from a string.
3024 :    
3025 :     =over 4
3026 :    
3027 :     =item sourceString
3028 :    
3029 :     String from which the random character should be selected.
3030 :    
3031 :     =item RETURN
3032 :    
3033 :     Returns a single character from the incoming string.
3034 :    
3035 :     =back
3036 :    
3037 :     =cut
3038 :    
3039 :     sub RandChar {
3040 : parrello 1.10 # Get the parameter.
3041 :     my ($sourceString) = @_;
3042 :     # Select a random character.
3043 :     my $retVal = IntGen(0, (length $sourceString) - 1);
3044 :     # Return it.
3045 :     return substr($sourceString, $retVal, 1);
3046 : parrello 1.1 }
3047 :    
3048 :     =head3 RandChars
3049 :    
3050 :     C<< my $string = RandChars($sourceString, $length); >>
3051 :    
3052 :     Create a string from characters taken from a source string.
3053 :    
3054 :     =over 4
3055 :    
3056 :     =item sourceString
3057 :    
3058 :     String from which the random characters should be selected.
3059 :    
3060 :     =item length
3061 :    
3062 :     Number of characters to put in the output string.
3063 :    
3064 :     =item RETURN
3065 :    
3066 :     Returns a string of the specified length consisting of characters taken from the
3067 :     source string.
3068 :    
3069 :     =back
3070 :    
3071 :     =cut
3072 :    
3073 :     sub RandChars {
3074 : parrello 1.10 # Get the parameters.
3075 :     my ($sourceString, $length) = @_;
3076 :     # Call RandChar repeatedly to generate the string.
3077 :     my $retVal = "";
3078 :     for (my $i = 0; $i < $length; $i++) {
3079 :     $retVal .= RandChar($sourceString);
3080 :     }
3081 :     # Return the result.
3082 :     return $retVal;
3083 : parrello 1.1 }
3084 :    
3085 :     =head3 RandParam
3086 :    
3087 :     C<< my $value = RandParam($parm1, $parm2, ... $parmN); >>
3088 :    
3089 :     Return a randomly-selected value from the parameter list.
3090 :    
3091 :     =over 4
3092 :    
3093 :     =item parm1, parm2, ... parmN
3094 :    
3095 :     List of values of which one will be selected.
3096 :    
3097 :     =item RETURN
3098 :    
3099 :     Returns a randomly-chosen value from the specified list.
3100 :    
3101 :     =back
3102 :    
3103 :     =cut
3104 :    
3105 :     sub RandParam {
3106 : parrello 1.10 # Get the parameter.
3107 :     my @parms = @_;
3108 :     # Choose a random parameter from the list.
3109 :     my $chosenIndex = IntGen(0, $#parms);
3110 :     return $parms[$chosenIndex];
3111 : parrello 1.1 }
3112 :    
3113 :     =head3 StringGen
3114 :    
3115 :     C<< my $string = StringGen($pattern1, $pattern2, ... $patternN); >>
3116 :    
3117 :     Returns a random string derived from a randomly-chosen format pattern. The pattern
3118 :     can either be a number (indicating the number of characters desired, or the letter
3119 :     C<P> followed by a picture. The picture should contain C<A> when a letter is desired,
3120 :     C<9> when a digit is desired, C<V> when a vowel is desired, C<K> when a consonant is
3121 :     desired, and C<X> when a letter or a digit is desired. Any other character will be
3122 :     translated as a literal.
3123 :    
3124 :     =over 4
3125 :    
3126 :     =item pattern1, pattern2, ... patternN
3127 :    
3128 :     List of patterns to be used to generate string values.
3129 :    
3130 :     =item RETURN
3131 :    
3132 :     A single string generated from a pattern.
3133 :    
3134 :     =back
3135 :    
3136 :     =cut
3137 :    
3138 :     sub StringGen {
3139 : parrello 1.10 # Get the parameters.
3140 :     my @patterns = @_;
3141 :     # Choose the appropriate pattern.
3142 :     my $chosenPattern = RandParam(@patterns);
3143 :     # Declare the return variable.
3144 :     my $retVal = "";
3145 :     # Determine whether this is a count or a picture pattern.
3146 :     if ($chosenPattern =~ m/^\d+/) {
3147 :     # Here we have a count. Get the string of source characters.
3148 :     my $letterString = $PictureTable{'X'};
3149 :     my $stringLen = length $letterString;
3150 :     # Save the number of characters we have to generate.
3151 :     my $charsLeft = $chosenPattern;
3152 :     # Loop until the return variable is full.
3153 :     while ($charsLeft > 0) {
3154 :     # Generate a random position in the soruce string.
3155 :     my $stringIndex = IntGen(0, $stringLen - 1);
3156 :     # Compute the number of characters to pull out of the source string.
3157 :     my $chunkSize = $stringLen - $stringIndex;
3158 :     if ($chunkSize > $charsLeft) { $chunkSize = $charsLeft; }
3159 :     # Stuff this chunk into the return value.
3160 :     $retVal .= substr($letterString, $stringIndex, $chunkSize);
3161 :     # Record the data moved.
3162 :     $charsLeft -= $chunkSize;
3163 :     }
3164 :     } elsif ($chosenPattern =~ m/^P/) {
3165 :     # Here we have a picture string. We will move through the picture one
3166 :     # character at a time generating data.
3167 :     for (my $i = 1; $i < length $chosenPattern; $i++) {
3168 :     # Get this picture character.
3169 :     my $chr = substr($chosenPattern, $i, 1);
3170 :     # Check to see if the picture char is one we recognize.
3171 :     if (exists $PictureTable{$chr}) {
3172 :     # Choose a random character from the available values for this
3173 :     # picture character.
3174 :     $retVal .= RandChar($PictureTable{$chr});
3175 :     } else {
3176 :     # Copy in the picture character as a literal.
3177 :     $retVal .= $chr;
3178 :     }
3179 :     }
3180 :     } else {
3181 :     # Here we have neither a picture string or a letter count, so we treat
3182 :     # the string as a literal.
3183 :     $retVal = $chosenPattern;
3184 :     }
3185 :     # Return the string formed.
3186 :     return $retVal;
3187 : parrello 1.1 }
3188 :    
3189 :     =head3 DateGen
3190 :    
3191 :     C<< my $date = DateGen($startDayOffset, $endDayOffset, $minutes); >>
3192 :    
3193 :     Return a numeric timestamp within the specified range of days with the specified minute
3194 :     value. The range of days is specified relevant to the current day. Thus, the call
3195 :    
3196 :     C<< my $date = DateGen(-1, 5, 720); >>
3197 :    
3198 :     will return a timestamp at noon (72 minutes past midnight) sometime during the week that
3199 :     began on the preceding day. If you want a random minute of the day, simply combine with
3200 :     a call to L</IntGen>, as follows.
3201 :    
3202 :     C<< my $date = DateGen(-1, 5, IntGen(0, 1439)); >>
3203 :    
3204 :     =over 4
3205 :    
3206 :     =item startDayOffset
3207 :    
3208 :     The earliest day that can be returned, relative to the current day.
3209 :    
3210 :     =item endDayOffset
3211 :    
3212 :     The latest day that can be returned, related to the current day.
3213 :    
3214 :     =item minutes
3215 :    
3216 :     Number of minutes into the selected day that should be used.
3217 :    
3218 :     =back
3219 :    
3220 :     =cut
3221 :    
3222 :     sub DateGen {
3223 : parrello 1.10 # Get the parameters.
3224 :     my ($startDayOffset, $endDayOffset, $minutes) = @_;
3225 :     # Get midnight of the current day.
3226 :     my $now = time();
3227 :     my ($sec, $min, $hour) = localtime($now);
3228 :     my $today = $now - (($hour * 60 + $min) * 60 + $sec);
3229 :     # Compute the day we want.
3230 :     my $newDay = IntGen($startDayOffset, $endDayOffset) * 86400 + $today;
3231 :     # Add the minutes.
3232 :     my $retVal = $newDay + $minutes * 60;
3233 :     # Return the result.
3234 :     return $retVal;
3235 : parrello 1.1 }
3236 :    
3237 :     =head3 FloatGen
3238 :    
3239 :     C<< my $number = FloatGen($min, $max); >>
3240 :    
3241 :     Return a random floating-point number greater than or equal to the specified minimum and
3242 :     less than the specified maximum.
3243 :    
3244 :     =over 4
3245 :    
3246 :     =item min
3247 :    
3248 :     Minimum permissible value for the number returned.
3249 :    
3250 :     =item max
3251 :    
3252 :     Maximum permissible value for the number returned.
3253 :    
3254 :     =item RETURN
3255 :    
3256 :     Returns a floating-point number anywhere in the specified range.
3257 :    
3258 :     =back
3259 :    
3260 :     =cut
3261 :    
3262 :     sub FloatGen {
3263 : parrello 1.10 # Get the parameters.
3264 :     my ($min, $max) = @_;
3265 :     # Generate the result.
3266 :     my $retVal = rand($max - $min) + $min;
3267 :     return $retVal;
3268 : parrello 1.1 }
3269 :    
3270 :     =head3 ListGen
3271 :    
3272 :     C<< my @list = ListGen($pattern, $count); >>
3273 :    
3274 :     Return a list containing a fixed number of randomly-generated strings.
3275 :    
3276 :     =over 4
3277 :    
3278 :     =item pattern
3279 :    
3280 :     A pattern (in the form expected by L</StringGen>) that should be used to generate the
3281 :     strings in the list.
3282 :    
3283 :     =item count
3284 :    
3285 :     The number of list entries to generate.
3286 :    
3287 :     =item RETURN
3288 :    
3289 :     Returns a list consisting of the specified number of strings.
3290 :    
3291 :     =back
3292 :    
3293 :     =cut
3294 :    
3295 :     sub ListGen {
3296 : parrello 1.10 # Get the parameters.
3297 :     my ($pattern, $count) = @_;
3298 :     # Generate the list.
3299 :     my @retVal = ();
3300 :     for (my $i = 0; $i < $count; $i++) {
3301 :     push @retVal, StringGen($pattern);
3302 :     }
3303 :     # Return it.
3304 :     return @retVal;
3305 : parrello 1.1 }
3306 :    
3307 : overbeek 1.11 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3