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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3