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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3