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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3