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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3