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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3