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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.47 - (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.42 use Digest::MD5 qw(md5_base64);
13 : parrello 1.19 use FIG;
14 : parrello 1.1
15 :     =head1 Entity-Relationship Database Package
16 :    
17 :     =head2 Introduction
18 :    
19 :     The Entity-Relationship Database Package allows the client to create an easily-configurable
20 :     database of Entities connected by Relationships. Each entity is represented by one or more
21 :     relations in an underlying SQL database. Each relationship is represented by a single
22 :     relation that connects two entities.
23 :    
24 :     Although this package is designed for general use, all examples are derived from the
25 :     Sprout database, which is the first database implemented using this package.
26 :    
27 :     Each entity has at least one relation, the I<primary relation>, that has the same name as
28 :     the entity. The primary relation contains a field named C<id> that contains the unique
29 :     identifier of each entity instance. An entity may have additional relations that contain
30 :     fields which are optional or can occur more than once. For example, the B<FEATURE> entity
31 :     has a B<feature-type> attribute that occurs exactly once for each feature. This attribute
32 :     is implemented by a C<feature_type> column in the primary relation C<Feature>. In addition,
33 :     however, a feature may have zero or more aliases. These are implemented using a C<FeatureAlias>
34 :     relation that contains two fields-- the feature ID (C<id>) and the alias name (C<alias>).
35 :     The B<FEATURE> entity also contains an optional virulence number. This is implemented
36 :     as a separate relation C<FeatureVirulence> which contains an ID (C<id>) and a virulence number
37 : parrello 1.8 (C<virulence>). If the virulence of a feature I<ABC> is known to be 6, there will be one row in
38 :     the C<FeatureVirulence> relation possessing the value I<ABC> as its ID and 6 as its virulence
39 :     number. If the virulence of I<ABC> is not known, there will not be any rows for it in
40 :     C<FeatureVirulence>.
41 : parrello 1.1
42 :     Entities are connected by binary relationships implemented using single relations possessing the
43 :     same name as the relationship itself and that has an I<arity> of 1-to-1 (C<11>), 1-to-many (C<1M>),
44 :     or many-to-many (C<MM>). Each relationship's relation contains a C<from-link> field that contains the
45 :     ID of the source entity and a C<to-link> field that contains the ID of the target entity. The name
46 :     of the relationship is generally a verb phrase with the source entity as the subject and the
47 :     target entity as the object. So, for example, the B<ComesFrom> relationship connects the B<GENOME>
48 :     and B<SOURCE> entities, and indicates that a particular source organization participated in the
49 :     mapping of the genome. A source organization frequently participates in the mapping
50 :     of many genomes, and many source organizations can cooperate in the mapping of a single genome, so
51 :     this relationship has an arity of many-to-many (C<MM>). The relation that implements the B<ComesFrom>
52 :     relationship is called C<ComesFrom> and contains two fields-- C<from-link>, which contains a genome ID,
53 :     and C<to-link>, which contains a source ID.
54 :    
55 :     A relationship may itself have attributes. These attributes, known as I<intersection data attributes>,
56 :     are implemented as additional fields in the relationship's relation. So, for example, the
57 :     B<IsMadeUpOf> relationship connects the B<Contig> entity to the B<Sequence> entity, and is used
58 :     to determine which sequences make up a contig. The relationship has as an attribute the
59 :     B<start-position>, which indicates where in the contig that the sequence begins. This attribute
60 :     is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.
61 :    
62 :     The database itself is described by an XML file using the F<ERDatabase.xsd> schema. In addition to
63 :     all the data required to define the entities, relationships, and attributes, the schema provides
64 :     space for notes describing the data and what it means. These notes are used by L</ShowMetaData>
65 :     to generate documentation for the database.
66 :    
67 :     Finally, every entity and relationship object has a flag indicating if it is new or old. The object
68 :     is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it
69 :     was inserted by the L</InsertObject> method.
70 :    
71 :     To facilitate testing, the ERDB module supports automatic generation of test data. This process
72 : parrello 1.5 is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet
73 :     fully implemented.
74 : parrello 1.1
75 : parrello 1.8 =head2 XML Database Description
76 :    
77 :     =head3 Data Types
78 :    
79 :     The ERDB system supports the following data types. Note that there are numerous string
80 :     types depending on the maximum length. Some database packages limit the total number of
81 :     characters you have in an index key; to insure the database works in all environments,
82 :     the type of string should be the shortest one possible that supports all the known values.
83 :    
84 :     =over 4
85 :    
86 :     =item char
87 :    
88 :     single ASCII character
89 :    
90 :     =item int
91 :    
92 :     32-bit signed integer
93 :    
94 :     =item date
95 :    
96 :     64-bit unsigned integer, representing a PERL date/time value
97 :    
98 :     =item text
99 :    
100 :     long string; Text fields cannot be used in indexes or sorting and do not support the
101 :     normal syntax of filter clauses, but can be up to a billion character in length
102 :    
103 :     =item float
104 :    
105 :     double-precision floating-point number
106 :    
107 :     =item boolean
108 :    
109 :     single-bit numeric value; The value is stored as a 16-bit signed integer (for
110 :     compatability with certain database packages), but the only values supported are
111 :     0 and 1.
112 :    
113 : parrello 1.44 =item id-string
114 :    
115 :     variable-length string, maximum 25 characters
116 :    
117 : parrello 1.8 =item key-string
118 :    
119 :     variable-length string, maximum 40 characters
120 :    
121 :     =item name-string
122 :    
123 :     variable-length string, maximum 80 characters
124 :    
125 :     =item medium-string
126 :    
127 :     variable-length string, maximum 160 characters
128 :    
129 :     =item string
130 :    
131 :     variable-length string, maximum 255 characters
132 :    
133 : parrello 1.42 =item hash-string
134 :    
135 :     variable-length string, maximum 22 characters
136 :    
137 : parrello 1.8 =back
138 :    
139 : parrello 1.42 The hash-string data type has a special meaning. The actual key passed into the loader will
140 :     be a string, but it will be digested into a 22-character MD5 code to save space. Although the
141 :     MD5 algorithm is not perfect, it is extremely unlikely two strings will have the same
142 :     digest. Therefore, it is presumed the keys will be unique. When the database is actually
143 :     in use, the hashed keys will be presented rather than the original values. For this reason,
144 :     they should not be used for entities where the key is meaningful.
145 :    
146 : parrello 1.8 =head3 Global Tags
147 :    
148 :     The entire database definition must be inside a B<Database> tag. The display name of
149 :     the database is given by the text associated with the B<Title> tag. The display name
150 :     is only used in the automated documentation. It has no other effect. The entities and
151 :     relationships are listed inside the B<Entities> and B<Relationships> tags,
152 :     respectively. None of these tags have attributes.
153 :    
154 : parrello 1.10 <Database>
155 :     <Title>... display title here...</Title>
156 :     <Entities>
157 :     ... entity definitions here ...
158 :     </Entities>
159 :     <Relationships>
160 :     ... relationship definitions here...
161 :     </Relationships>
162 :     </Database>
163 : parrello 1.8
164 :     Entities, relationships, indexes, and fields all allow a text tag called B<Notes>.
165 :     The text inside the B<Notes> tag contains comments that will appear when the database
166 :     documentation is generated. Within a B<Notes> tag, you may use C<[i]> and C<[/i]> for
167 :     italics, C<[b]> and C<[/b]> for bold, and C<[p]> for a new paragraph.
168 :    
169 :     =head3 Fields
170 :    
171 :     Both entities and relationships have fields described by B<Field> tags. A B<Field>
172 :     tag can have B<Notes> associated with it. The complete set of B<Field> tags for an
173 :     object mus be inside B<Fields> tags.
174 :    
175 : parrello 1.10 <Entity ... >
176 :     <Fields>
177 :     ... Field tags ...
178 :     </Fields>
179 :     </Entity>
180 : parrello 1.8
181 :     The attributes for the B<Field> tag are as follows.
182 :    
183 :     =over 4
184 :    
185 :     =item name
186 :    
187 :     Name of the field. The field name should contain only letters, digits, and hyphens (C<->),
188 :     and the first character should be a letter. Most underlying databases are case-insensitive
189 :     with the respect to field names, so a best practice is to use lower-case letters only.
190 :    
191 :     =item type
192 :    
193 :     Data type of the field. The legal data types are given above.
194 :    
195 :     =item relation
196 :    
197 :     Name of the relation containing the field. This should only be specified for entity
198 :     fields. The ERDB system does not support optional fields or multi-occurring fields
199 :     in the primary relation of an entity. Instead, they are put into secondary relations.
200 :     So, for example, in the C<Genome> entity, the C<group-name> field indicates a special
201 :     grouping used to select a subset of the genomes. A given genome may not be in any
202 :     groups or may be in multiple groups. Therefore, C<group-name> specifies a relation
203 :     value. The relation name specified must be a valid table name. By convention, it is
204 :     usually the entity name followed by a qualifying word (e.g. C<GenomeGroup>). In an
205 :     entity, the fields without a relation attribute are said to belong to the
206 :     I<primary relation>. This relation has the same name as the entity itself.
207 :    
208 :     =back
209 :    
210 :     =head3 Indexes
211 :    
212 :     An entity can have multiple alternate indexes associated with it. The fields must
213 :     be from the primary relation. The alternate indexes assist in ordering results
214 :     from a query. A relationship can have up to two indexes-- a I<to-index> and a
215 :     I<from-index>. These order the results when crossing the relationship. For
216 :     example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
217 :     from-index would order the contigs of a ganome, and the to-index would order
218 :     the genomes of a contig. A relationship's index must specify only fields in
219 :     the relationship.
220 :    
221 :     The indexes for an entity must be listed inside the B<Indexes> tag. The from-index
222 :     of a relationship is specified using the B<FromIndex> tag; the to-index is specified
223 :     using the B<ToIndex> tag.
224 :    
225 :     Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
226 :     tag containing the B<IndexField> tags. These specify, in order, the fields used in
227 :     the index. The attributes of an B<IndexField> tag are as follows.
228 :    
229 :     =over 4
230 :    
231 :     =item name
232 :    
233 :     Name of the field.
234 :    
235 :     =item order
236 :    
237 :     Sort order of the field-- C<ascending> or C<descending>.
238 :    
239 :     =back
240 :    
241 :     The B<Index>, B<FromIndex>, and B<ToIndex> tags themselves have no attributes.
242 :    
243 :     =head3 Object and Field Names
244 :    
245 :     By convention entity and relationship names use capital casing (e.g. C<Genome> or
246 :     C<HasRegionsIn>. Most underlying databases, however, are aggressively case-insensitive
247 :     with respect to relation names, converting them internally to all-upper case or
248 :     all-lower case.
249 :    
250 :     If syntax or parsing errors occur when you try to load or use an ERDB database, the
251 :     most likely reason is that one of your objects has an SQL reserved word as its name.
252 :     The list of SQL reserved words keeps increasing; however, most are unlikely to show
253 :     up as a noun or declarative verb phrase. The exceptions are C<Group>, C<User>,
254 :     C<Table>, C<Index>, C<Object>, C<Date>, C<Number>, C<Update>, C<Time>, C<Percent>,
255 :     C<Memo>, C<Order>, and C<Sum>. This problem can crop up in field names as well.
256 :    
257 :     Every entity has a field called C<id> that acts as its primary key. Every relationship
258 :     has fields called C<from-link> and C<to-link> that contain copies of the relevant
259 :     entity IDs. These are essentially ERDB's reserved words, and should not be used
260 :     for user-defined field names.
261 :    
262 :     =head3 Entities
263 :    
264 :     An entity is described by the B<Entity> tag. The entity can contain B<Notes>, an
265 :     B<Indexes> tag containing one or more secondary indexes, and a B<Fields> tag
266 :     containing one or more fields. The attributes of the B<Entity> tag are as follows.
267 :    
268 :     =over 4
269 :    
270 :     =item name
271 :    
272 :     Name of the entity. The entity name, by convention, uses capital casing (e.g. C<Genome>
273 :     or C<GroupBlock>) and should be a noun or noun phrase.
274 :    
275 :     =item keyType
276 :    
277 :     Data type of the primary key. The primary key is always named C<id>.
278 :    
279 :     =back
280 :    
281 :     =head3 Relationships
282 :    
283 :     A relationship is described by the C<Relationship> tag. Within a relationship,
284 :     there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
285 :     fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing
286 :     the to-index.
287 :    
288 :     The C<Relationship> tag has the following attributes.
289 :    
290 :     =over 4
291 :    
292 :     =item name
293 :    
294 :     Name of the relationship. The relationship name, by convention, uses capital casing
295 :     (e.g. C<ContainsRegionIn> or C<HasContig>), and should be a declarative verb
296 :     phrase, designed to fit between the from-entity and the to-entity (e.g.
297 :     Block C<ContainsRegionIn> Genome).
298 :    
299 :     =item from
300 :    
301 :     Name of the entity from which the relationship starts.
302 :    
303 :     =item to
304 :    
305 :     Name of the entity to which the relationship proceeds.
306 :    
307 :     =item arity
308 :    
309 :     Relationship type: C<1M> for one-to-many and C<MM> for many-to-many.
310 :    
311 :     =back
312 :    
313 : parrello 1.1 =cut
314 :    
315 :     # GLOBALS
316 :    
317 :     # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.
318 :     # "maxLen" is the maximum permissible length of the incoming string data used to populate a field
319 :     # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation
320 : parrello 1.18 # string is specified in the field definition. "avgLen" is the average byte length for estimating
321 :     # record sizes.
322 :     my %TypeTable = ( char => { sqlType => 'CHAR(1)', maxLen => 1, avgLen => 1, dataGen => "StringGen('A')" },
323 :     int => { sqlType => 'INTEGER', maxLen => 20, avgLen => 4, dataGen => "IntGen(0, 99999999)" },
324 :     string => { sqlType => 'VARCHAR(255)', maxLen => 255, avgLen => 100, dataGen => "StringGen(IntGen(10,250))" },
325 :     text => { sqlType => 'TEXT', maxLen => 1000000000, avgLen => 500, dataGen => "StringGen(IntGen(80,1000))" },
326 :     date => { sqlType => 'BIGINT', maxLen => 80, avgLen => 8, dataGen => "DateGen(-7, 7, IntGen(0,1400))" },
327 :     float => { sqlType => 'DOUBLE PRECISION', maxLen => 40, avgLen => 8, dataGen => "FloatGen(0.0, 100.0)" },
328 : parrello 1.31 boolean => { sqlType => 'SMALLINT', maxLen => 1, avgLen => 1, dataGen => "IntGen(0, 1)" },
329 : parrello 1.42 'hash-string' =>
330 :     { sqlType => 'VARCHAR(22)', maxLen => 22, avgLen => 22, dataGen => "SringGen(22)" },
331 : parrello 1.44 'id-string' =>
332 :     { sqlType => 'VARCHAR(25)', maxLen => 25, avgLen => 25, dataGen => "SringGen(22)" },
333 : parrello 1.10 'key-string' =>
334 : parrello 1.18 { sqlType => 'VARCHAR(40)', maxLen => 40, avgLen => 10, dataGen => "StringGen(IntGen(10,40))" },
335 : parrello 1.10 'name-string' =>
336 : parrello 1.18 { sqlType => 'VARCHAR(80)', maxLen => 80, avgLen => 40, dataGen => "StringGen(IntGen(10,80))" },
337 : parrello 1.10 'medium-string' =>
338 : parrello 1.18 { sqlType => 'VARCHAR(160)', maxLen => 160, avgLen => 40, dataGen => "StringGen(IntGen(10,160))" },
339 : parrello 1.10 );
340 : parrello 1.1
341 :     # Table translating arities into natural language.
342 :     my %ArityTable = ( '11' => 'one-to-one',
343 : parrello 1.10 '1M' => 'one-to-many',
344 :     'MM' => 'many-to-many'
345 :     );
346 : parrello 1.1
347 :     # Table for interpreting string patterns.
348 :    
349 :     my %PictureTable = ( 'A' => "abcdefghijklmnopqrstuvwxyz",
350 : parrello 1.10 '9' => "0123456789",
351 :     'X' => "abcdefghijklmnopqrstuvwxyz0123456789",
352 :     'V' => "aeiou",
353 :     'K' => "bcdfghjklmnoprstvwxyz"
354 :     );
355 : parrello 1.1
356 :     =head2 Public Methods
357 :    
358 :     =head3 new
359 :    
360 : parrello 1.5 C<< my $database = ERDB->new($dbh, $metaFileName); >>
361 : parrello 1.1
362 :     Create a new ERDB object.
363 :    
364 :     =over 4
365 :    
366 :     =item dbh
367 :    
368 :     DBKernel database object for the target database.
369 :    
370 :     =item metaFileName
371 :    
372 :     Name of the XML file containing the metadata.
373 :    
374 :     =back
375 :    
376 :     =cut
377 :    
378 :     sub new {
379 : parrello 1.10 # Get the parameters.
380 :     my ($class, $dbh, $metaFileName, $options) = @_;
381 :     # Load the meta-data.
382 :     my $metaData = _LoadMetaData($metaFileName);
383 :     # Create the object.
384 :     my $self = { _dbh => $dbh,
385 :     _metaData => $metaData
386 :     };
387 :     # Bless and return it.
388 :     bless $self, $class;
389 :     return $self;
390 : parrello 1.1 }
391 :    
392 :     =head3 ShowMetaData
393 :    
394 : parrello 1.18 C<< $erdb->ShowMetaData($fileName); >>
395 : parrello 1.1
396 :     This method outputs a description of the database. This description can be used to help users create
397 :     the data to be loaded into the relations.
398 :    
399 :     =over 4
400 :    
401 :     =item filename
402 :    
403 :     The name of the output file.
404 :    
405 :     =back
406 :    
407 :     =cut
408 :    
409 :     sub ShowMetaData {
410 : parrello 1.10 # Get the parameters.
411 :     my ($self, $filename) = @_;
412 :     # Get the metadata and the title string.
413 :     my $metadata = $self->{_metaData};
414 :     # Get the title string.
415 :     my $title = $metadata->{Title};
416 :     # Get the entity and relationship lists.
417 :     my $entityList = $metadata->{Entities};
418 :     my $relationshipList = $metadata->{Relationships};
419 :     # Open the output file.
420 :     open(HTMLOUT, ">$filename") || Confess("Could not open MetaData display file $filename: $!");
421 :     Trace("Building MetaData table of contents.") if T(4);
422 :     # Write the HTML heading stuff.
423 :     print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
424 :     print HTMLOUT "</head>\n<body>\n";
425 : parrello 1.45 # Write the documentation.
426 :     print HTMLOUT $self->DisplayMetaData();
427 :     # Close the document.
428 :     print HTMLOUT "</body>\n</html>\n";
429 :     # Close the file.
430 :     close HTMLOUT;
431 :     }
432 :    
433 :     =head3 DisplayMetaData
434 :    
435 :     C<< my $html = $erdb->DisplayMetaData(); >>
436 :    
437 :     Return an HTML description of the database. This description can be used to help users create
438 :     the data to be loaded into the relations and form queries. The output is raw includable HTML
439 :     without any HEAD or BODY tags.
440 :    
441 :     =over 4
442 :    
443 :     =item filename
444 :    
445 :     The name of the output file.
446 :    
447 :     =back
448 :    
449 :     =cut
450 :    
451 :     sub DisplayMetaData {
452 :     # Get the parameters.
453 :     my ($self) = @_;
454 :     # Get the metadata and the title string.
455 :     my $metadata = $self->{_metaData};
456 :     # Get the title string.
457 :     my $title = $metadata->{Title};
458 :     # Get the entity and relationship lists.
459 :     my $entityList = $metadata->{Entities};
460 :     my $relationshipList = $metadata->{Relationships};
461 :     # Declare the return variable.
462 :     my $retVal = "";
463 :     # Open the output file.
464 :     Trace("Building MetaData table of contents.") if T(4);
465 : parrello 1.10 # Here we do the table of contents. It starts as an unordered list of section names. Each
466 :     # section contains an ordered list of entity or relationship subsections.
467 : parrello 1.45 $retVal .= "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n";
468 : parrello 1.10 # Loop through the Entities, displaying a list item for each.
469 :     foreach my $key (sort keys %{$entityList}) {
470 :     # Display this item.
471 : parrello 1.45 $retVal .= "<li><a href=\"#$key\">$key</a></li>\n";
472 : parrello 1.10 }
473 :     # Close off the entity section and start the relationship section.
474 : parrello 1.45 $retVal .= "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n";
475 : parrello 1.10 # Loop through the Relationships.
476 :     foreach my $key (sort keys %{$relationshipList}) {
477 :     # Display this item.
478 :     my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
479 : parrello 1.45 $retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
480 : parrello 1.10 }
481 :     # Close off the relationship section and list the join table section.
482 : parrello 1.45 $retVal .= "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n";
483 : parrello 1.10 # Close off the table of contents itself.
484 : parrello 1.45 $retVal .= "</ul>\n";
485 : parrello 1.10 # Now we start with the actual data. Denote we're starting the entity section.
486 : parrello 1.45 $retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
487 : parrello 1.10 # Loop through the entities.
488 :     for my $key (sort keys %{$entityList}) {
489 :     Trace("Building MetaData entry for $key entity.") if T(4);
490 :     # Create the entity header. It contains a bookmark and the entity name.
491 : parrello 1.45 $retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n";
492 : parrello 1.10 # Get the entity data.
493 :     my $entityData = $entityList->{$key};
494 :     # If there's descriptive text, display it.
495 :     if (my $notes = $entityData->{Notes}) {
496 : parrello 1.45 $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
497 : parrello 1.10 }
498 :     # Now we want a list of the entity's relationships. First, we set up the relationship subsection.
499 : parrello 1.45 $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
500 : parrello 1.10 # Loop through the relationships.
501 :     for my $relationship (sort keys %{$relationshipList}) {
502 :     # Get the relationship data.
503 :     my $relationshipStructure = $relationshipList->{$relationship};
504 :     # Only use the relationship if if has this entity in its FROM or TO fields.
505 :     if ($relationshipStructure->{from} eq $key || $relationshipStructure->{to} eq $key) {
506 :     # Get the relationship sentence and append the arity.
507 :     my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
508 :     # Display the relationship data.
509 : parrello 1.45 $retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
510 : parrello 1.10 }
511 :     }
512 :     # Close off the relationship list.
513 : parrello 1.45 $retVal .= "</ul>\n";
514 : parrello 1.10 # Get the entity's relations.
515 :     my $relationList = $entityData->{Relations};
516 :     # Create a header for the relation subsection.
517 : parrello 1.45 $retVal .= "<h4>Relations for <b>$key</b></h4>\n";
518 : parrello 1.10 # Loop through the relations, displaying them.
519 :     for my $relation (sort keys %{$relationList}) {
520 :     my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
521 : parrello 1.45 $retVal .= $htmlString;
522 : parrello 1.10 }
523 :     }
524 :     # Denote we're starting the relationship section.
525 : parrello 1.45 $retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
526 : parrello 1.10 # Loop through the relationships.
527 :     for my $key (sort keys %{$relationshipList}) {
528 :     Trace("Building MetaData entry for $key relationship.") if T(4);
529 :     # Get the relationship's structure.
530 :     my $relationshipStructure = $relationshipList->{$key};
531 :     # Create the relationship header.
532 :     my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
533 : parrello 1.45 $retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n";
534 : parrello 1.10 # Get the entity names.
535 :     my $fromEntity = $relationshipStructure->{from};
536 :     my $toEntity = $relationshipStructure->{to};
537 :     # Describe the relationship arity. Note there's a bit of trickiness involving recursive
538 :     # many-to-many relationships. In a normal many-to-many we use two sentences to describe
539 :     # the arity (one for each direction). This is a bad idea for a recursive relationship,
540 :     # since both sentences will say the same thing.
541 :     my $arity = $relationshipStructure->{arity};
542 :     if ($arity eq "11") {
543 : parrello 1.45 $retVal .= "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n";
544 : parrello 1.10 } else {
545 : parrello 1.45 $retVal .= "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n";
546 : parrello 1.10 if ($arity eq "MM" && $fromEntity ne $toEntity) {
547 : parrello 1.45 $retVal .= "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n";
548 : parrello 1.10 }
549 :     }
550 : parrello 1.45 $retVal .= "</p>\n";
551 : parrello 1.10 # If there are notes on this relationship, display them.
552 :     if (my $notes = $relationshipStructure->{Notes}) {
553 : parrello 1.45 $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
554 : parrello 1.10 }
555 :     # Generate the relationship's relation table.
556 :     my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
557 : parrello 1.45 $retVal .= $htmlString;
558 : parrello 1.10 }
559 :     Trace("Building MetaData join table.") if T(4);
560 :     # Denote we're starting the join table.
561 : parrello 1.45 $retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
562 : parrello 1.10 # Create a table header.
563 : parrello 1.45 $retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition");
564 : parrello 1.10 # Loop through the joins.
565 :     my $joinTable = $metadata->{Joins};
566 :     my @joinKeys = keys %{$joinTable};
567 :     for my $joinKey (sort @joinKeys) {
568 :     # Separate out the source, the target, and the join clause.
569 :     $joinKey =~ m!^([^/]+)/(.+)$!;
570 :     my ($sourceRelation, $targetRelation) = ($1, $2);
571 : parrello 1.30 Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(Joins => 4);
572 : parrello 1.10 my $source = $self->ComputeObjectSentence($sourceRelation);
573 :     my $target = $self->ComputeObjectSentence($targetRelation);
574 :     my $clause = $joinTable->{$joinKey};
575 :     # Display them in a table row.
576 : parrello 1.45 $retVal .= "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";
577 : parrello 1.10 }
578 :     # Close the table.
579 : parrello 1.45 $retVal .= _CloseTable();
580 :     Trace("Built MetaData HTML.") if T(3);
581 :     # Return the HTML.
582 :     return $retVal;
583 : parrello 1.1 }
584 :    
585 :     =head3 DumpMetaData
586 :    
587 : parrello 1.18 C<< $erdb->DumpMetaData(); >>
588 : parrello 1.1
589 :     Return a dump of the metadata structure.
590 :    
591 :     =cut
592 :    
593 :     sub DumpMetaData {
594 : parrello 1.10 # Get the parameters.
595 :     my ($self) = @_;
596 :     # Dump the meta-data.
597 :     return Data::Dumper::Dumper($self->{_metaData});
598 : parrello 1.1 }
599 :    
600 :     =head3 CreateTables
601 :    
602 : parrello 1.18 C<< $erdb->CreateTables(); >>
603 : parrello 1.1
604 :     This method creates the tables for the database from the metadata structure loaded by the
605 :     constructor. It is expected this function will only be used on rare occasions, when the
606 : parrello 1.2 user needs to start with an empty database. Otherwise, the L</LoadTables> method can be
607 : parrello 1.1 used by itself with the truncate flag turned on.
608 :    
609 :     =cut
610 :    
611 :     sub CreateTables {
612 : parrello 1.10 # Get the parameters.
613 :     my ($self) = @_;
614 : parrello 1.23 # Get the relation names.
615 :     my @relNames = $self->GetTableNames();
616 :     # Loop through the relations.
617 :     for my $relationName (@relNames) {
618 :     # Create a table for this relation.
619 :     $self->CreateTable($relationName);
620 :     Trace("Relation $relationName created.") if T(2);
621 : parrello 1.10 }
622 : parrello 1.1 }
623 :    
624 :     =head3 CreateTable
625 :    
626 : parrello 1.18 C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>
627 : parrello 1.1
628 :     Create the table for a relation and optionally create its indexes.
629 :    
630 :     =over 4
631 :    
632 :     =item relationName
633 :    
634 :     Name of the relation (which will also be the table name).
635 :    
636 : parrello 1.18 =item indexFlag
637 : parrello 1.1
638 :     TRUE if the indexes for the relation should be created, else FALSE. If FALSE,
639 :     L</CreateIndexes> must be called later to bring the indexes into existence.
640 :    
641 : parrello 1.18 =item estimatedRows (optional)
642 :    
643 :     If specified, the estimated maximum number of rows for the relation. This
644 :     information allows the creation of tables using storage engines that are
645 :     faster but require size estimates, such as MyISAM.
646 :    
647 : parrello 1.1 =back
648 :    
649 :     =cut
650 :    
651 :     sub CreateTable {
652 : parrello 1.10 # Get the parameters.
653 : parrello 1.18 my ($self, $relationName, $indexFlag, $estimatedRows) = @_;
654 : parrello 1.10 # Get the database handle.
655 :     my $dbh = $self->{_dbh};
656 :     # Get the relation data and determine whether or not the relation is primary.
657 :     my $relationData = $self->_FindRelation($relationName);
658 :     my $rootFlag = $self->_IsPrimary($relationName);
659 :     # Create a list of the field data.
660 :     my @fieldList;
661 :     for my $fieldData (@{$relationData->{Fields}}) {
662 :     # Assemble the field name and type.
663 :     my $fieldName = _FixName($fieldData->{name});
664 :     my $fieldString = "$fieldName $TypeTable{$fieldData->{type}}->{sqlType} NOT NULL ";
665 :     # Push the result into the field list.
666 :     push @fieldList, $fieldString;
667 :     }
668 :     # If this is a root table, add the "new_record" flag. It defaults to 0, so
669 :     if ($rootFlag) {
670 :     push @fieldList, "new_record $TypeTable{boolean}->{sqlType} NOT NULL DEFAULT 0";
671 :     }
672 :     # Convert the field list into a comma-delimited string.
673 :     my $fieldThing = join(', ', @fieldList);
674 :     # Insure the table is not already there.
675 :     $dbh->drop_table(tbl => $relationName);
676 :     Trace("Table $relationName dropped.") if T(2);
677 : parrello 1.18 # If there are estimated rows, create an estimate so we can take advantage of
678 :     # faster DB technologies.
679 :     my $estimation = undef;
680 :     if ($estimatedRows) {
681 :     $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
682 :     }
683 : parrello 1.10 # Create the table.
684 :     Trace("Creating table $relationName: $fieldThing") if T(2);
685 : parrello 1.18 $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);
686 : parrello 1.10 Trace("Relation $relationName created in database.") if T(2);
687 :     # If we want to build the indexes, we do it here.
688 :     if ($indexFlag) {
689 :     $self->CreateIndex($relationName);
690 :     }
691 : parrello 1.1 }
692 :    
693 : parrello 1.31 =head3 VerifyFields
694 :    
695 :     C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>
696 :    
697 :     Run through the list of proposed field values, insuring that all the character fields are
698 :     below the maximum length. If any fields are too long, they will be truncated in place.
699 :    
700 :     =over 4
701 :    
702 :     =item relName
703 :    
704 :     Name of the relation for which the specified fields are destined.
705 :    
706 :     =item fieldList
707 :    
708 :     Reference to a list, in order, of the fields to be put into the relation.
709 :    
710 :     =item RETURN
711 :    
712 :     Returns the number of fields truncated.
713 :    
714 :     =back
715 :    
716 :     =cut
717 :    
718 :     sub VerifyFields {
719 :     # Get the parameters.
720 :     my ($self, $relName, $fieldList) = @_;
721 :     # Initialize the return value.
722 :     my $retVal = 0;
723 :     # Get the relation definition.
724 :     my $relData = $self->_FindRelation($relName);
725 :     # Get the list of field descriptors.
726 :     my $fieldTypes = $relData->{Fields};
727 :     my $fieldCount = scalar @{$fieldTypes};
728 :     # Loop through the two lists.
729 :     for (my $i = 0; $i < $fieldCount; $i++) {
730 :     # Get the type of the current field.
731 :     my $fieldType = $fieldTypes->[$i]->{type};
732 :     # If it's a character field, verify the length.
733 :     if ($fieldType =~ /string/) {
734 :     my $maxLen = $TypeTable{$fieldType}->{maxLen};
735 :     my $oldString = $fieldList->[$i];
736 :     if (length($oldString) > $maxLen) {
737 :     # Here it's too big, so we truncate it.
738 :     Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
739 :     $fieldList->[$i] = substr $oldString, 0, $maxLen;
740 :     $retVal++;
741 :     }
742 :     }
743 :     }
744 :     # Return the truncation count.
745 :     return $retVal;
746 :     }
747 :    
748 : parrello 1.42 =head3 DigestFields
749 :    
750 :     C<< $erdb->DigestFields($relName, $fieldList); >>
751 :    
752 :     Digest the strings in the field list that correspond to data type C<hash-string> in the
753 :     specified relation.
754 :    
755 :     =over 4
756 :    
757 :     =item relName
758 :    
759 :     Name of the relation to which the fields belong.
760 :    
761 :     =item fieldList
762 :    
763 :     List of field contents to be loaded into the relation.
764 :    
765 :     =back
766 :    
767 :     =cut
768 :     #: Return Type ;
769 :     sub DigestFields {
770 :     # Get the parameters.
771 :     my ($self, $relName, $fieldList) = @_;
772 :     # Get the relation definition.
773 :     my $relData = $self->_FindRelation($relName);
774 :     # Get the list of field descriptors.
775 :     my $fieldTypes = $relData->{Fields};
776 :     my $fieldCount = scalar @{$fieldTypes};
777 :     # Loop through the two lists.
778 :     for (my $i = 0; $i < $fieldCount; $i++) {
779 :     # Get the type of the current field.
780 :     my $fieldType = $fieldTypes->[$i]->{type};
781 :     # If it's a hash string, digest it in place.
782 :     if ($fieldType eq 'hash-string') {
783 : parrello 1.46 $fieldList->[$i] = $self->DigestKey($fieldList->[$i]);
784 : parrello 1.42 }
785 :     }
786 :     }
787 :    
788 : parrello 1.46 =head3 DigestKey
789 :    
790 :     C<< my $digested = $erdb->DigestKey($keyValue); >>
791 :    
792 :     Return the digested value of a symbolic key. The digested value can then be plugged into a
793 :     key-based search into a table with key-type hash-string.
794 :    
795 :     Currently the digesting process is independent of the database structure, but that may not
796 :     always be the case, so this is an instance method instead of a static method.
797 :    
798 :     =over 4
799 :    
800 :     =item keyValue
801 :    
802 :     Key value to digest.
803 :    
804 :     =item RETURN
805 :    
806 :     Digested value ofthe key.
807 :    
808 :     =back
809 :    
810 :     =cut
811 :    
812 :     sub DigestKey {
813 :     # Get the parameters.
814 :     my ($self, $keyValue) = @_;
815 :     # Compute the digest.
816 :     my $retVal = md5_base64($keyValue);
817 :     # Return the result.
818 :     return $retVal;
819 :     }
820 :    
821 : parrello 1.1 =head3 CreateIndex
822 :    
823 : parrello 1.18 C<< $erdb->CreateIndex($relationName); >>
824 : parrello 1.1
825 :     Create the indexes for a relation. If a table is being loaded from a large source file (as
826 : parrello 1.12 is the case in L</LoadTable>), it is sometimes best to create the indexes after the load.
827 :     If that is the case, then L</CreateTable> should be called with the index flag set to
828 :     FALSE, and this method used after the load to create the indexes for the table.
829 : parrello 1.1
830 :     =cut
831 :    
832 :     sub CreateIndex {
833 : parrello 1.10 # Get the parameters.
834 :     my ($self, $relationName) = @_;
835 :     # Get the relation's descriptor.
836 :     my $relationData = $self->_FindRelation($relationName);
837 :     # Get the database handle.
838 :     my $dbh = $self->{_dbh};
839 :     # Now we need to create this relation's indexes. We do this by looping through its index table.
840 :     my $indexHash = $relationData->{Indexes};
841 :     for my $indexName (keys %{$indexHash}) {
842 :     my $indexData = $indexHash->{$indexName};
843 :     # Get the index's field list.
844 :     my @fieldList = _FixNames(@{$indexData->{IndexFields}});
845 :     my $flds = join(', ', @fieldList);
846 :     # Get the index's uniqueness flag.
847 :     my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');
848 :     # Create the index.
849 : parrello 1.24 my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
850 :     flds => $flds, unique => $unique);
851 :     if ($rv) {
852 :     Trace("Index created: $indexName for $relationName ($flds)") if T(1);
853 :     } else {
854 :     Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
855 :     }
856 : parrello 1.10 }
857 : parrello 1.1 }
858 :    
859 :     =head3 LoadTables
860 :    
861 : parrello 1.18 C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>
862 : parrello 1.1
863 :     This method will load the database tables from a directory. The tables must already have been created
864 :     in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
865 :     all of the relations to be loaded must have a file in the directory with the same name as the relation
866 :     (optionally with a suffix of C<.dtx>). Each file must be a tab-delimited table of field values. Each
867 :     line of the file will be loaded as a row of the target relation table. The field values should be in
868 :     the same order as the fields in the relation tables generated by L</ShowMetaData>. The old data is
869 :     erased before the new data is loaded in.
870 :    
871 :     A certain amount of translation automatically takes place. Ctrl-M characters are deleted, and
872 :     tab and new-line characters inside a field are escaped as C<\t> and C<\n>, respectively. Dates must
873 :     be entered as a Unix timestamp, that is, as an integer number of seconds since the base epoch.
874 :    
875 :     =over 4
876 :    
877 :     =item directoryName
878 :    
879 :     Name of the directory containing the relation files to be loaded.
880 :    
881 :     =item rebuild
882 :    
883 :     TRUE if the tables should be dropped and rebuilt, else FALSE. This is, unfortunately, the
884 :     only way to erase existing data in the tables, since the TRUNCATE command is not supported
885 :     by all of the DB engines we use.
886 :    
887 :     =item RETURN
888 :    
889 :     Returns a statistical object describing the number of records read and a list of the error messages.
890 :    
891 :     =back
892 :    
893 :     =cut
894 :    
895 :     sub LoadTables {
896 : parrello 1.10 # Get the parameters.
897 :     my ($self, $directoryName, $rebuild) = @_;
898 :     # Start the timer.
899 :     my $startTime = gettimeofday;
900 :     # Clean any trailing slash from the directory name.
901 :     $directoryName =~ s!/\\$!!;
902 :     # Declare the return variable.
903 :     my $retVal = Stats->new();
904 : parrello 1.23 # Get the relation names.
905 :     my @relNames = $self->GetTableNames();
906 :     for my $relationName (@relNames) {
907 :     # Try to load this relation.
908 :     my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
909 : parrello 1.10 # Accumulate the statistics.
910 :     $retVal->Accumulate($result);
911 :     }
912 :     # Add the duration of the load to the statistical object.
913 :     $retVal->Add('duration', gettimeofday - $startTime);
914 :     # Return the accumulated statistics.
915 :     return $retVal;
916 : parrello 1.1 }
917 :    
918 : parrello 1.23
919 : parrello 1.1 =head3 GetTableNames
920 :    
921 : parrello 1.18 C<< my @names = $erdb->GetTableNames; >>
922 : parrello 1.1
923 :     Return a list of the relations required to implement this database.
924 :    
925 :     =cut
926 :    
927 :     sub GetTableNames {
928 : parrello 1.10 # Get the parameters.
929 :     my ($self) = @_;
930 :     # Get the relation list from the metadata.
931 :     my $relationTable = $self->{_metaData}->{RelationTable};
932 :     # Return the relation names.
933 :     return keys %{$relationTable};
934 : parrello 1.1 }
935 :    
936 :     =head3 GetEntityTypes
937 :    
938 : parrello 1.18 C<< my @names = $erdb->GetEntityTypes; >>
939 : parrello 1.1
940 :     Return a list of the entity type names.
941 :    
942 :     =cut
943 :    
944 :     sub GetEntityTypes {
945 : parrello 1.10 # Get the database object.
946 :     my ($self) = @_;
947 :     # Get the entity list from the metadata object.
948 :     my $entityList = $self->{_metaData}->{Entities};
949 :     # Return the list of entity names in alphabetical order.
950 :     return sort keys %{$entityList};
951 : parrello 1.1 }
952 :    
953 : parrello 1.20 =head3 IsEntity
954 :    
955 :     C<< my $flag = $erdb->IsEntity($entityName); >>
956 :    
957 :     Return TRUE if the parameter is an entity name, else FALSE.
958 :    
959 :     =over 4
960 :    
961 :     =item entityName
962 :    
963 :     Object name to be tested.
964 :    
965 :     =item RETURN
966 :    
967 :     Returns TRUE if the specified string is an entity name, else FALSE.
968 :    
969 :     =back
970 :    
971 :     =cut
972 :    
973 :     sub IsEntity {
974 :     # Get the parameters.
975 :     my ($self, $entityName) = @_;
976 :     # Test to see if it's an entity.
977 :     return exists $self->{_metaData}->{Entities}->{$entityName};
978 :     }
979 :    
980 : parrello 1.1 =head3 Get
981 :    
982 : parrello 1.45 C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>
983 : parrello 1.1
984 :     This method returns a query object for entities of a specified type using a specified filter.
985 :     The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
986 :     field name represented in the form B<I<objectName>(I<fieldName>)>. For example, the
987 :     following call requests all B<Genome> objects for the genus specified in the variable
988 :     $genus.
989 :    
990 : parrello 1.45 C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>
991 : parrello 1.1
992 :     The WHERE clause contains a single question mark, so there is a single additional
993 :     parameter representing the parameter value. It would also be possible to code
994 :    
995 : parrello 1.18 C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>
996 : parrello 1.1
997 :     however, this version of the call would generate a syntax error if there were any quote
998 :     characters inside the variable C<$genus>.
999 :    
1000 :     The use of the strange parenthesized notation for field names enables us to distinguish
1001 :     hyphens contained within field names from minus signs that participate in the computation
1002 :     of the WHERE clause. All of the methods that manipulate fields will use this same notation.
1003 :    
1004 :     It is possible to specify multiple entity and relationship names in order to retrieve more than
1005 :     one object's data at the same time, which allows highly complex joined queries. For example,
1006 :    
1007 : parrello 1.45 C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>
1008 : parrello 1.1
1009 :     If multiple names are specified, then the query processor will automatically determine a
1010 :     join path between the entities and relationships. The algorithm used is very simplistic.
1011 : parrello 1.39 In particular, if a relationship is recursive, the path is determined by the order in which
1012 :     the entity and the relationship appear. For example, consider a recursive relationship
1013 :     B<IsParentOf> which relates B<People> objects to other B<People> objects. If the join path is
1014 : parrello 1.1 coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,
1015 :     the join path is C<['IsParentOf', 'People']>, then the people returned will be children.
1016 :    
1017 : parrello 1.39 If an entity or relationship is mentioned twice, the name for the second occurrence will
1018 :     be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
1019 :     for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
1020 :     B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
1021 :     the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
1022 :    
1023 : parrello 1.1 =over 4
1024 :    
1025 :     =item objectNames
1026 :    
1027 :     List containing the names of the entity and relationship objects to be retrieved.
1028 :    
1029 :     =item filterClause
1030 :    
1031 :     WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1032 :     be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1033 :     specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1034 :     in the filter clause should be added to the parameter list as additional parameters. The
1035 :     fields in a filter clause can come from primary entity relations, relationship relations,
1036 :     or secondary entity relations; however, all of the entities and relationships involved must
1037 :     be included in the list of object names.
1038 :    
1039 :     The filter clause can also specify a sort order. To do this, simply follow the filter string
1040 :     with an ORDER BY clause. For example, the following filter string gets all genomes for a
1041 :     particular genus and sorts them by species name.
1042 :    
1043 :     C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1044 :    
1045 : parrello 1.30 Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1046 :     be processed. The idea is to make it less likely to find the verb by accident.
1047 :    
1048 : parrello 1.1 The rules for field references in a sort order are the same as those for field references in the
1049 :     filter clause in general; however, odd things may happen if a sort field is from a secondary
1050 :     relation.
1051 :    
1052 : parrello 1.39 Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1053 :     be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1054 :     a positive number. So, for example
1055 :    
1056 :     C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>
1057 :    
1058 :     will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1059 :     required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1060 :     use
1061 :    
1062 :     C<< "LIMIT 10" >>
1063 :    
1064 : parrello 1.45 =item params
1065 : parrello 1.1
1066 : parrello 1.45 Reference to a list of parameter values to be substituted into the filter clause.
1067 : parrello 1.1
1068 :     =item RETURN
1069 :    
1070 :     Returns a B<DBQuery> that can be used to iterate through all of the results.
1071 :    
1072 :     =back
1073 :    
1074 :     =cut
1075 :    
1076 :     sub Get {
1077 : parrello 1.10 # Get the parameters.
1078 : parrello 1.45 my ($self, $objectNames, $filterClause, $params) = @_;
1079 :     # Process the SQL stuff.
1080 :     my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1081 :     $self->_SetupSQL($objectNames, $filterClause);
1082 :     # Create the query.
1083 :     my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .
1084 :     ".* $suffix";
1085 :     my $sth = $self->_GetStatementHandle($command, $params);
1086 : parrello 1.39 # Now we create the relation map, which enables DBQuery to determine the order, name
1087 :     # and mapped name for each object in the query.
1088 :     my @relationMap = ();
1089 : parrello 1.45 for my $mappedName (@{$mappedNameListRef}) {
1090 :     push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}];
1091 : parrello 1.39 }
1092 : parrello 1.10 # Return the statement object.
1093 : parrello 1.39 my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1094 : parrello 1.10 return $retVal;
1095 : parrello 1.1 }
1096 :    
1097 : parrello 1.45 =head3 GetFlat
1098 :    
1099 :     C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>
1100 :    
1101 :     This is a variation of L</GetAll> that asks for only a single field per record and
1102 :     returns a single flattened list.
1103 :    
1104 :     =over 4
1105 :    
1106 :     =item objectNames
1107 :    
1108 :     List containing the names of the entity and relationship objects to be retrieved.
1109 :    
1110 :     =item filterClause
1111 :    
1112 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1113 :     be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1114 :     B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1115 :     parameter list as additional parameters. The fields in a filter clause can come from primary
1116 :     entity relations, relationship relations, or secondary entity relations; however, all of the
1117 :     entities and relationships involved must be included in the list of object names.
1118 :    
1119 :     =item parameterList
1120 :    
1121 :     List of the parameters to be substituted in for the parameters marks in the filter clause.
1122 :    
1123 :     =item field
1124 :    
1125 :     Name of the field to be used to get the elements of the list returned.
1126 :    
1127 :     =item RETURN
1128 :    
1129 :     Returns a list of values.
1130 :    
1131 :     =back
1132 :    
1133 :     =cut
1134 :     #: Return Type @;
1135 :     sub GetFlat {
1136 :     # Get the parameters.
1137 :     my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1138 :     # Construct the query.
1139 :     my $query = $self->Get($objectNames, $filterClause, $parameterList);
1140 :     # Create the result list.
1141 :     my @retVal = ();
1142 :     # Loop through the records, adding the field values found to the result list.
1143 :     while (my $row = $query->Fetch()) {
1144 :     push @retVal, $row->Value($field);
1145 :     }
1146 :     # Return the list created.
1147 :     return @retVal;
1148 :     }
1149 :    
1150 : parrello 1.32 =head3 Delete
1151 :    
1152 :     C<< my $stats = $erdb->Delete($entityName, $objectID); >>
1153 :    
1154 :     Delete an entity instance from the database. The instance is deleted along with all entity and
1155 :     relationship instances dependent on it. The idea of dependence here is recursive. An object is
1156 :     always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1157 :     relationship connected to a dependent entity or the "to" entity connected to a 1-to-many
1158 :     dependent relationship.
1159 :    
1160 :     =over 4
1161 :    
1162 :     =item entityName
1163 :    
1164 :     Name of the entity type for the instance being deleted.
1165 :    
1166 :     =item objectID
1167 :    
1168 :     ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1169 :     then it is presumed to by a LIKE pattern.
1170 :    
1171 :     =item testFlag
1172 :    
1173 :     If TRUE, the delete statements will be traced without being executed.
1174 :    
1175 :     =item RETURN
1176 :    
1177 :     Returns a statistics object indicating how many records of each particular table were
1178 :     deleted.
1179 :    
1180 :     =back
1181 :    
1182 :     =cut
1183 :     #: Return Type $%;
1184 :     sub Delete {
1185 :     # Get the parameters.
1186 :     my ($self, $entityName, $objectID, $testFlag) = @_;
1187 :     # Declare the return variable.
1188 :     my $retVal = Stats->new();
1189 :     # Get the DBKernel object.
1190 :     my $db = $self->{_dbh};
1191 :     # We're going to generate all the paths branching out from the starting entity. One of
1192 :     # the things we have to be careful about is preventing loops. We'll use a hash to
1193 :     # determine if we've hit a loop.
1194 :     my %alreadyFound = ();
1195 : parrello 1.33 # These next lists will serve as our result stack. We start by pushing object lists onto
1196 : parrello 1.32 # the stack, and then popping them off to do the deletes. This means the deletes will
1197 :     # start with the longer paths before getting to the shorter ones. That, in turn, makes
1198 :     # sure we don't delete records that might be needed to forge relationships back to the
1199 : parrello 1.33 # original item. We have two lists-- one for TO-relationships, and one for
1200 :     # FROM-relationships and entities.
1201 :     my @fromPathList = ();
1202 :     my @toPathList = ();
1203 : parrello 1.32 # This final hash is used to remember what work still needs to be done. We push paths
1204 :     # onto the list, then pop them off to extend the paths. We prime it with the starting
1205 :     # point. Note that we will work hard to insure that the last item on a path in the
1206 :     # TODO list is always an entity.
1207 :     my @todoList = ([$entityName]);
1208 :     while (@todoList) {
1209 :     # Get the current path.
1210 :     my $current = pop @todoList;
1211 :     # Copy it into a list.
1212 :     my @stackedPath = @{$current};
1213 :     # Pull off the last item on the path. It will always be an entity.
1214 :     my $entityName = pop @stackedPath;
1215 :     # Add it to the alreadyFound list.
1216 :     $alreadyFound{$entityName} = 1;
1217 :     # Get the entity data.
1218 :     my $entityData = $self->_GetStructure($entityName);
1219 :     # The first task is to loop through the entity's relation. A DELETE command will
1220 :     # be needed for each of them.
1221 :     my $relations = $entityData->{Relations};
1222 :     for my $relation (keys %{$relations}) {
1223 :     my @augmentedList = (@stackedPath, $relation);
1224 : parrello 1.33 push @fromPathList, \@augmentedList;
1225 : parrello 1.32 }
1226 :     # Now we need to look for relationships connected to this entity.
1227 :     my $relationshipList = $self->{_metaData}->{Relationships};
1228 :     for my $relationshipName (keys %{$relationshipList}) {
1229 :     my $relationship = $relationshipList->{$relationshipName};
1230 :     # Check the FROM field. We're only interested if it's us.
1231 :     if ($relationship->{from} eq $entityName) {
1232 :     # Add the path to this relationship.
1233 :     my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1234 : parrello 1.33 push @fromPathList, \@augmentedList;
1235 : parrello 1.32 # Check the arity. If it's MM we're done. If it's 1M
1236 :     # and the target hasn't been seen yet, we want to
1237 :     # stack the entity for future processing.
1238 :     if ($relationship->{arity} eq '1M') {
1239 :     my $toEntity = $relationship->{to};
1240 :     if (! exists $alreadyFound{$toEntity}) {
1241 :     # Here we have a new entity that's dependent on
1242 :     # the current entity, so we need to stack it.
1243 :     my @stackList = (@augmentedList, $toEntity);
1244 : parrello 1.33 push @fromPathList, \@stackList;
1245 : parrello 1.34 } else {
1246 :     Trace("$toEntity ignored because it occurred previously.") if T(4);
1247 : parrello 1.32 }
1248 :     }
1249 :     }
1250 :     # Now check the TO field. In this case only the relationship needs
1251 : parrello 1.33 # deletion.
1252 : parrello 1.32 if ($relationship->{to} eq $entityName) {
1253 :     my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1254 : parrello 1.33 push @toPathList, \@augmentedList;
1255 : parrello 1.32 }
1256 :     }
1257 :     }
1258 :     # Create the first qualifier for the WHERE clause. This selects the
1259 :     # keys of the primary entity records to be deleted. When we're deleting
1260 :     # from a dependent table, we construct a join page from the first qualifier
1261 :     # to the table containing the dependent records to delete.
1262 :     my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
1263 : parrello 1.33 # We need to make two passes. The first is through the to-list, and
1264 :     # the second through the from-list. The from-list is second because
1265 :     # the to-list may need to pass through some of the entities the
1266 :     # from-list would delete.
1267 :     my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
1268 :     # Now it's time to do the deletes. We do it in two passes.
1269 :     for my $keyName ('to_link', 'from_link') {
1270 :     # Get the list for this key.
1271 :     my @pathList = @{$stackList{$keyName}};
1272 : parrello 1.34 Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
1273 : parrello 1.33 # Loop through this list.
1274 :     while (my $path = pop @pathList) {
1275 :     # Get the table whose rows are to be deleted.
1276 :     my @pathTables = @{$path};
1277 : parrello 1.37 # Start the DELETE statement. We need to call DBKernel because the
1278 :     # syntax of a DELETE-USING varies among DBMSs.
1279 : parrello 1.33 my $target = $pathTables[$#pathTables];
1280 : parrello 1.37 my $stmt = $db->SetUsing(@pathTables);
1281 : parrello 1.33 # Now start the WHERE. The first thing is the ID field from the starting table. That
1282 :     # starting table will either be the entity relation or one of the entity's
1283 :     # sub-relations.
1284 :     $stmt .= " WHERE $pathTables[0].id $qualifier";
1285 :     # Now we run through the remaining entities in the path, connecting them up.
1286 :     for (my $i = 1; $i <= $#pathTables; $i += 2) {
1287 :     # Connect the current relationship to the preceding entity.
1288 :     my ($entity, $rel) = @pathTables[$i-1,$i];
1289 :     # The style of connection depends on the direction of the relationship.
1290 : parrello 1.35 $stmt .= " AND $entity.id = $rel.$keyName";
1291 : parrello 1.32 if ($i + 1 <= $#pathTables) {
1292 :     # Here there's a next entity, so connect that to the relationship's
1293 :     # to-link.
1294 :     my $entity2 = $pathTables[$i+1];
1295 : parrello 1.35 $stmt .= " AND $rel.to_link = $entity2.id";
1296 : parrello 1.32 }
1297 :     }
1298 : parrello 1.33 # Now we have our desired DELETE statement.
1299 :     if ($testFlag) {
1300 :     # Here the user wants to trace without executing.
1301 :     Trace($stmt) if T(0);
1302 :     } else {
1303 :     # Here we can delete. Note that the SQL method dies with a confessing
1304 :     # if an error occurs, so we just go ahead and do it.
1305 : parrello 1.36 Trace("Executing delete from $target using '$objectID'.") if T(3);
1306 :     my $rv = $db->SQL($stmt, 0, $objectID);
1307 : parrello 1.33 # Accumulate the statistics for this delete. The only rows deleted
1308 :     # are from the target table, so we use its name to record the
1309 :     # statistic.
1310 :     $retVal->Add($target, $rv);
1311 :     }
1312 : parrello 1.32 }
1313 :     }
1314 :     # Return the result.
1315 :     return $retVal;
1316 :     }
1317 :    
1318 : parrello 1.6 =head3 GetList
1319 :    
1320 : parrello 1.45 C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>
1321 : parrello 1.6
1322 :     Return a list of object descriptors for the specified objects as determined by the
1323 :     specified filter clause.
1324 :    
1325 :     This method is essentially the same as L</Get> except it returns a list of objects rather
1326 : parrello 1.7 than a query object that can be used to get the results one record at a time.
1327 : parrello 1.6
1328 :     =over 4
1329 :    
1330 :     =item objectNames
1331 :    
1332 :     List containing the names of the entity and relationship objects to be retrieved.
1333 :    
1334 :     =item filterClause
1335 :    
1336 :     WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1337 :     be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1338 :     specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1339 :     in the filter clause should be added to the parameter list as additional parameters. The
1340 :     fields in a filter clause can come from primary entity relations, relationship relations,
1341 :     or secondary entity relations; however, all of the entities and relationships involved must
1342 :     be included in the list of object names.
1343 :    
1344 :     The filter clause can also specify a sort order. To do this, simply follow the filter string
1345 :     with an ORDER BY clause. For example, the following filter string gets all genomes for a
1346 :     particular genus and sorts them by species name.
1347 :    
1348 :     C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1349 :    
1350 :     The rules for field references in a sort order are the same as those for field references in the
1351 :     filter clause in general; however, odd things may happen if a sort field is from a secondary
1352 :     relation.
1353 :    
1354 : parrello 1.45 =item params
1355 : parrello 1.6
1356 : parrello 1.45 Reference to a list of parameter values to be substituted into the filter clause.
1357 : parrello 1.6
1358 :     =item RETURN
1359 :    
1360 :     Returns a list of B<DBObject>s that satisfy the query conditions.
1361 :    
1362 :     =back
1363 :    
1364 :     =cut
1365 :     #: Return Type @%
1366 :     sub GetList {
1367 :     # Get the parameters.
1368 : parrello 1.45 my ($self, $objectNames, $filterClause, $params) = @_;
1369 : parrello 1.10 # Declare the return variable.
1370 :     my @retVal = ();
1371 :     # Perform the query.
1372 : parrello 1.45 my $query = $self->Get($objectNames, $filterClause, $params);
1373 : parrello 1.10 # Loop through the results.
1374 :     while (my $object = $query->Fetch) {
1375 :     push @retVal, $object;
1376 :     }
1377 : parrello 1.6 # Return the result.
1378 :     return @retVal;
1379 :     }
1380 :    
1381 : parrello 1.45 =head3 GetCount
1382 :    
1383 :     C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>
1384 :    
1385 :     Return the number of rows found by a specified query. This method would
1386 :     normally be used to count the records in a single table. For example, in a
1387 :     genetics database
1388 :    
1389 :     my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
1390 :    
1391 :     would return the number of genomes for the genus I<homo>. It is conceivable, however,
1392 :     to use it to return records based on a join. For example,
1393 :    
1394 : parrello 1.47 my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?',
1395 : parrello 1.45 ['homo %']);
1396 :    
1397 :     would return the number of features for genomes in the genus I<homo>. Note that
1398 :     only the rows from the first table are counted. If the above command were
1399 :    
1400 :     my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
1401 :     ['homo %']);
1402 :    
1403 :     it would return the number of genomes, not the number of genome/feature pairs.
1404 :    
1405 :     =over 4
1406 :    
1407 :     =item objectNames
1408 :    
1409 :     Reference to a list of the objects (entities and relationships) included in the
1410 :     query.
1411 :    
1412 :     =item filter
1413 :    
1414 :     A filter clause for restricting the query. The rules are the same as for the L</Get>
1415 :     method.
1416 :    
1417 :     =item params
1418 :    
1419 :     Reference to a list of the parameter values to be substituted for the parameter marks
1420 :     in the filter.
1421 :    
1422 :     =item RETURN
1423 :    
1424 :     Returns a count of the number of records in the first table that would satisfy
1425 :     the query.
1426 :    
1427 :     =back
1428 :    
1429 :     =cut
1430 :    
1431 :     sub GetCount {
1432 :     # Get the parameters.
1433 :     my ($self, $objectNames, $filter, $params) = @_;
1434 :     # Declare the return variable.
1435 :     my $retVal;
1436 : parrello 1.47 # Find out if we're counting an entity or a relationship.
1437 :     my $countedField;
1438 :     if ($self->IsEntity($objectNames->[0])) {
1439 :     $countedField = "id";
1440 :     } else {
1441 :     # For a relationship we count the to-link because it's usually more
1442 :     # numerous. Note we're automatically converting to the SQL form
1443 :     # of the field name (to_link vs. to-link).
1444 :     $countedField = "to_link";
1445 :     }
1446 : parrello 1.45 # Create the SQL command suffix to get the desired records.
1447 :     my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1448 :     $filter);
1449 :     # Prefix it with text telling it we want a record count.
1450 :     my $firstObject = $mappedNameListRef->[0];
1451 : parrello 1.47 my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
1452 : parrello 1.45 # Prepare and execute the command.
1453 :     my $sth = $self->_GetStatementHandle($command, $params);
1454 :     # Get the count value.
1455 :     ($retVal) = $sth->fetchrow_array();
1456 :     # Check for a problem.
1457 :     if (! defined($retVal)) {
1458 :     if ($sth->err) {
1459 :     # Here we had an SQL error.
1460 :     Confess("Error retrieving row count: " . $sth->errstr());
1461 :     } else {
1462 :     # Here we have no result.
1463 :     Confess("No result attempting to retrieve row count.");
1464 :     }
1465 :     }
1466 :     # Return the result.
1467 :     return $retVal;
1468 :     }
1469 :    
1470 : parrello 1.1 =head3 ComputeObjectSentence
1471 :    
1472 : parrello 1.18 C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>
1473 : parrello 1.1
1474 :     Check an object name, and if it is a relationship convert it to a relationship sentence.
1475 :    
1476 :     =over 4
1477 :    
1478 :     =item objectName
1479 :    
1480 :     Name of the entity or relationship.
1481 :    
1482 :     =item RETURN
1483 :    
1484 :     Returns a string containing the entity name or a relationship sentence.
1485 :    
1486 :     =back
1487 :    
1488 :     =cut
1489 :    
1490 :     sub ComputeObjectSentence {
1491 : parrello 1.10 # Get the parameters.
1492 :     my ($self, $objectName) = @_;
1493 :     # Set the default return value.
1494 :     my $retVal = $objectName;
1495 :     # Look for the object as a relationship.
1496 :     my $relTable = $self->{_metaData}->{Relationships};
1497 :     if (exists $relTable->{$objectName}) {
1498 :     # Get the relationship sentence.
1499 :     $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});
1500 :     }
1501 :     # Return the result.
1502 :     return $retVal;
1503 : parrello 1.1 }
1504 :    
1505 :     =head3 DumpRelations
1506 :    
1507 : parrello 1.18 C<< $erdb->DumpRelations($outputDirectory); >>
1508 : parrello 1.1
1509 :     Write the contents of all the relations to tab-delimited files in the specified directory.
1510 :     Each file will have the same name as the relation dumped, with an extension of DTX.
1511 :    
1512 :     =over 4
1513 :    
1514 :     =item outputDirectory
1515 :    
1516 :     Name of the directory into which the relation files should be dumped.
1517 :    
1518 :     =back
1519 :    
1520 :     =cut
1521 :    
1522 :     sub DumpRelations {
1523 : parrello 1.10 # Get the parameters.
1524 :     my ($self, $outputDirectory) = @_;
1525 :     # Now we need to run through all the relations. First, we loop through the entities.
1526 :     my $metaData = $self->{_metaData};
1527 :     my $entities = $metaData->{Entities};
1528 :     for my $entityName (keys %{$entities}) {
1529 :     my $entityStructure = $entities->{$entityName};
1530 :     # Get the entity's relations.
1531 :     my $relationList = $entityStructure->{Relations};
1532 :     # Loop through the relations, dumping them.
1533 :     for my $relationName (keys %{$relationList}) {
1534 :     my $relation = $relationList->{$relationName};
1535 :     $self->_DumpRelation($outputDirectory, $relationName, $relation);
1536 :     }
1537 :     }
1538 :     # Next, we loop through the relationships.
1539 :     my $relationships = $metaData->{Relationships};
1540 :     for my $relationshipName (keys %{$relationships}) {
1541 :     my $relationshipStructure = $relationships->{$relationshipName};
1542 :     # Dump this relationship's relation.
1543 :     $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
1544 :     }
1545 : parrello 1.1 }
1546 :    
1547 :     =head3 InsertObject
1548 :    
1549 : parrello 1.18 C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>
1550 : parrello 1.1
1551 :     Insert an object into the database. The object is defined by a type name and then a hash
1552 :     of field names to values. Field values in the primary relation are represented by scalars.
1553 :     (Note that for relationships, the primary relation is the B<only> relation.)
1554 :     Field values for the other relations comprising the entity are always list references. For
1555 :     example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
1556 :     C<ZP_00210270.1> and C<gi|46206278>.
1557 :    
1558 : parrello 1.18 C<< $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>
1559 : parrello 1.1
1560 :     The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
1561 :     property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
1562 :    
1563 : 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'}); >>
1564 : parrello 1.1
1565 :     =over 4
1566 :    
1567 :     =item newObjectType
1568 :    
1569 :     Type name of the object to insert.
1570 :    
1571 :     =item fieldHash
1572 :    
1573 :     Hash of field names to values.
1574 :    
1575 :     =item RETURN
1576 :    
1577 :     Returns 1 if successful, 0 if an error occurred.
1578 :    
1579 :     =back
1580 :    
1581 :     =cut
1582 :    
1583 :     sub InsertObject {
1584 : parrello 1.10 # Get the parameters.
1585 :     my ($self, $newObjectType, $fieldHash) = @_;
1586 :     # Denote that so far we appear successful.
1587 :     my $retVal = 1;
1588 :     # Get the database handle.
1589 :     my $dbh = $self->{_dbh};
1590 :     # Get the relation list.
1591 :     my $relationTable = $self->_GetRelationTable($newObjectType);
1592 :     # Loop through the relations. We'll build insert statements for each one. If a relation is
1593 :     # secondary, we may end up generating multiple insert statements. If an error occurs, we
1594 :     # stop the loop.
1595 :     my @relationList = keys %{$relationTable};
1596 :     for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
1597 :     my $relationName = $relationList[$i];
1598 :     my $relationDefinition = $relationTable->{$relationName};
1599 :     # Get the relation's fields. For each field we will collect a value in the corresponding
1600 :     # position of the @valueList array. If one of the fields is missing, we will add it to the
1601 :     # @missing list.
1602 :     my @fieldList = @{$relationDefinition->{Fields}};
1603 :     my @fieldNameList = ();
1604 :     my @valueList = ();
1605 :     my @missing = ();
1606 :     my $recordCount = 1;
1607 :     for my $fieldDescriptor (@fieldList) {
1608 :     # Get the field name and save it. Note we need to fix it up so the hyphens
1609 :     # are converted to underscores.
1610 :     my $fieldName = $fieldDescriptor->{name};
1611 :     push @fieldNameList, _FixName($fieldName);
1612 :     # Look for the named field in the incoming structure. Note that we are looking
1613 :     # for the real field name, not the fixed-up one!
1614 :     if (exists $fieldHash->{$fieldName}) {
1615 :     # Here we found the field. Stash it in the value list.
1616 :     my $value = $fieldHash->{$fieldName};
1617 :     push @valueList, $value;
1618 :     # If the value is a list, we may need to increment the record count.
1619 :     if (ref $value eq "ARRAY") {
1620 :     my $thisCount = @{$value};
1621 :     if ($recordCount == 1) {
1622 :     # Here we have our first list, so we save its count.
1623 :     $recordCount = $thisCount;
1624 :     } elsif ($recordCount != $thisCount) {
1625 :     # Here we have a second list, so its length has to match the
1626 :     # previous lists.
1627 :     Trace("Field $value in new $newObjectType object has an invalid list length $thisCount. Expected $recordCount.") if T(0);
1628 :     $retVal = 0;
1629 :     }
1630 :     }
1631 :     } else {
1632 :     # Here the field is not present. Flag it as missing.
1633 :     push @missing, $fieldName;
1634 :     }
1635 :     }
1636 :     # If we are the primary relation, add the new-record flag.
1637 :     if ($relationName eq $newObjectType) {
1638 :     push @valueList, 1;
1639 :     push @fieldNameList, "new_record";
1640 :     }
1641 :     # Only proceed if there are no missing fields.
1642 :     if (@missing > 0) {
1643 :     Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
1644 :     join(' ', @missing)) if T(1);
1645 :     } else {
1646 :     # Build the INSERT statement.
1647 :     my $statement = "INSERT INTO $relationName (" . join (', ', @fieldNameList) .
1648 :     ") VALUES (";
1649 :     # Create a marker list of the proper size and put it in the statement.
1650 :     my @markers = ();
1651 :     while (@markers < @fieldNameList) { push @markers, '?'; }
1652 :     $statement .= join(', ', @markers) . ")";
1653 :     # We have the insert statement, so prepare it.
1654 :     my $sth = $dbh->prepare_command($statement);
1655 :     Trace("Insert statement prepared: $statement") if T(3);
1656 :     # Now we loop through the values. If a value is scalar, we use it unmodified. If it's
1657 :     # a list, we use the current element. The values are stored in the @parameterList array.
1658 :     my $done = 0;
1659 :     for (my $i = 0; $i < $recordCount; $i++) {
1660 :     # Clear the parameter list array.
1661 :     my @parameterList = ();
1662 :     # Loop through the values.
1663 :     for my $value (@valueList) {
1664 :     # Check to see if this is a scalar value.
1665 :     if (ref $value eq "ARRAY") {
1666 :     # Here we have a list value. Pull the current entry.
1667 :     push @parameterList, $value->[$i];
1668 :     } else {
1669 :     # Here we have a scalar value. Use it unmodified.
1670 :     push @parameterList, $value;
1671 :     }
1672 :     }
1673 :     # Execute the INSERT statement with the specified parameter list.
1674 :     $retVal = $sth->execute(@parameterList);
1675 :     if (!$retVal) {
1676 :     my $errorString = $sth->errstr();
1677 :     Trace("Insert error: $errorString.") if T(0);
1678 :     }
1679 :     }
1680 :     }
1681 :     }
1682 :     # Return the success indicator.
1683 :     return $retVal;
1684 : parrello 1.1 }
1685 :    
1686 :     =head3 LoadTable
1687 :    
1688 : parrello 1.18 C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>
1689 : parrello 1.1
1690 : parrello 1.9 Load data from a tab-delimited file into a specified table, optionally re-creating the table
1691 :     first.
1692 : parrello 1.1
1693 :     =over 4
1694 :    
1695 :     =item fileName
1696 :    
1697 :     Name of the file from which the table data should be loaded.
1698 :    
1699 :     =item relationName
1700 :    
1701 :     Name of the relation to be loaded. This is the same as the table name.
1702 :    
1703 :     =item truncateFlag
1704 :    
1705 :     TRUE if the table should be dropped and re-created, else FALSE
1706 :    
1707 :     =item RETURN
1708 :    
1709 : parrello 1.28 Returns a statistical object containing a list of the error messages.
1710 : parrello 1.1
1711 :     =back
1712 :    
1713 :     =cut
1714 :     sub LoadTable {
1715 : parrello 1.10 # Get the parameters.
1716 :     my ($self, $fileName, $relationName, $truncateFlag) = @_;
1717 :     # Create the statistical return object.
1718 :     my $retVal = _GetLoadStats();
1719 :     # Trace the fact of the load.
1720 :     Trace("Loading table $relationName from $fileName") if T(2);
1721 :     # Get the database handle.
1722 :     my $dbh = $self->{_dbh};
1723 : parrello 1.22 # Get the input file size.
1724 :     my $fileSize = -s $fileName;
1725 : parrello 1.10 # Get the relation data.
1726 :     my $relation = $self->_FindRelation($relationName);
1727 :     # Check the truncation flag.
1728 :     if ($truncateFlag) {
1729 :     Trace("Creating table $relationName") if T(2);
1730 : parrello 1.19 # Compute the row count estimate. We take the size of the load file,
1731 :     # divide it by the estimated row size, and then multiply by 1.5 to
1732 :     # leave extra room. We postulate a minimum row count of 1000 to
1733 :     # prevent problems with incoming empty load files.
1734 :     my $rowSize = $self->EstimateRowSize($relationName);
1735 :     my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1736 : parrello 1.10 # Re-create the table without its index.
1737 : parrello 1.19 $self->CreateTable($relationName, 0, $estimate);
1738 : parrello 1.10 # If this is a pre-index DBMS, create the index here.
1739 :     if ($dbh->{_preIndex}) {
1740 :     eval {
1741 :     $self->CreateIndex($relationName);
1742 :     };
1743 :     if ($@) {
1744 :     $retVal->AddMessage($@);
1745 :     }
1746 :     }
1747 :     }
1748 : parrello 1.3 # Load the table.
1749 : parrello 1.10 my $rv;
1750 :     eval {
1751 : parrello 1.20 $rv = $dbh->load_table(file => $fileName, tbl => $relationName);
1752 : parrello 1.10 };
1753 :     if (!defined $rv) {
1754 : parrello 1.3 $retVal->AddMessage($@) if ($@);
1755 : parrello 1.20 $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1756 : parrello 1.10 Trace("Table load failed for $relationName.") if T(1);
1757 :     } else {
1758 : parrello 1.22 # Here we successfully loaded the table.
1759 :     $retVal->Add("tables");
1760 :     my $size = -s $fileName;
1761 :     Trace("$size bytes loaded into $relationName.") if T(2);
1762 : parrello 1.10 # If we're rebuilding, we need to create the table indexes.
1763 :     if ($truncateFlag && ! $dbh->{_preIndex}) {
1764 :     eval {
1765 :     $self->CreateIndex($relationName);
1766 :     };
1767 :     if ($@) {
1768 :     $retVal->AddMessage($@);
1769 :     }
1770 :     }
1771 :     }
1772 : parrello 1.20 # Analyze the table to improve performance.
1773 : olson 1.16 $dbh->vacuum_it($relationName);
1774 : parrello 1.10 # Return the statistics.
1775 :     return $retVal;
1776 : parrello 1.1 }
1777 :    
1778 :     =head3 GenerateEntity
1779 :    
1780 : parrello 1.18 C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>
1781 : parrello 1.1
1782 :     Generate the data for a new entity instance. This method creates a field hash suitable for
1783 :     passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest
1784 :     of the fields are generated using information in the database schema.
1785 :    
1786 :     Each data type has a default algorithm for generating random test data. This can be overridden
1787 :     by including a B<DataGen> element in the field. If this happens, the content of the element is
1788 :     executed as a PERL program in the context of this module. The element may make use of a C<$this>
1789 :     variable which contains the field hash as it has been built up to the current point. If any
1790 :     fields are dependent on other fields, the C<pass> attribute can be used to control the order
1791 :     in which the fields are generated. A field with a high data pass number will be generated after
1792 :     a field with a lower one. If any external values are needed, they should be passed in via the
1793 :     optional third parameter, which will be available to the data generation script under the name
1794 :     C<$value>. Several useful utility methods are provided for generating random values, including
1795 :     L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated
1796 :     in the form of a timestamp number rather than a string.
1797 :    
1798 :     =over 4
1799 :    
1800 :     =item id
1801 :    
1802 :     ID to assign to the new entity.
1803 :    
1804 :     =item type
1805 :    
1806 :     Type name for the new entity.
1807 :    
1808 :     =item values
1809 :    
1810 :     Hash containing additional values that might be needed by the data generation methods (optional).
1811 :    
1812 :     =back
1813 :    
1814 :     =cut
1815 :    
1816 :     sub GenerateEntity {
1817 : parrello 1.10 # Get the parameters.
1818 :     my ($self, $id, $type, $values) = @_;
1819 :     # Create the return hash.
1820 :     my $this = { id => $id };
1821 :     # Get the metadata structure.
1822 :     my $metadata = $self->{_metaData};
1823 :     # Get this entity's list of fields.
1824 :     if (!exists $metadata->{Entities}->{$type}) {
1825 :     Confess("Unrecognized entity type $type in GenerateEntity.");
1826 :     } else {
1827 :     my $entity = $metadata->{Entities}->{$type};
1828 :     my $fields = $entity->{Fields};
1829 :     # Generate data from the fields.
1830 :     _GenerateFields($this, $fields, $type, $values);
1831 :     }
1832 :     # Return the hash created.
1833 :     return $this;
1834 : parrello 1.1 }
1835 :    
1836 : parrello 1.6 =head3 GetEntity
1837 :    
1838 : parrello 1.18 C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>
1839 : parrello 1.6
1840 :     Return an object describing the entity instance with a specified ID.
1841 :    
1842 :     =over 4
1843 :    
1844 :     =item entityType
1845 :    
1846 :     Entity type name.
1847 :    
1848 :     =item ID
1849 :    
1850 :     ID of the desired entity.
1851 :    
1852 :     =item RETURN
1853 :    
1854 :     Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
1855 :     instance is found with the specified key.
1856 :    
1857 :     =back
1858 :    
1859 :     =cut
1860 :    
1861 :     sub GetEntity {
1862 : parrello 1.10 # Get the parameters.
1863 :     my ($self, $entityType, $ID) = @_;
1864 :     # Create a query.
1865 : parrello 1.45 my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
1866 : parrello 1.10 # Get the first (and only) object.
1867 :     my $retVal = $query->Fetch();
1868 :     # Return the result.
1869 :     return $retVal;
1870 : parrello 1.6 }
1871 :    
1872 :     =head3 GetEntityValues
1873 :    
1874 : parrello 1.18 C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>
1875 : parrello 1.6
1876 :     Return a list of values from a specified entity instance.
1877 :    
1878 :     =over 4
1879 :    
1880 :     =item entityType
1881 :    
1882 :     Entity type name.
1883 :    
1884 :     =item ID
1885 :    
1886 :     ID of the desired entity.
1887 :    
1888 :     =item fields
1889 :    
1890 :     List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
1891 :    
1892 :     =item RETURN
1893 :    
1894 :     Returns a flattened list of the values of the specified fields for the specified entity.
1895 :    
1896 :     =back
1897 :    
1898 :     =cut
1899 :    
1900 :     sub GetEntityValues {
1901 : parrello 1.10 # Get the parameters.
1902 :     my ($self, $entityType, $ID, $fields) = @_;
1903 :     # Get the specified entity.
1904 :     my $entity = $self->GetEntity($entityType, $ID);
1905 :     # Declare the return list.
1906 :     my @retVal = ();
1907 :     # If we found the entity, push the values into the return list.
1908 :     if ($entity) {
1909 :     push @retVal, $entity->Values($fields);
1910 :     }
1911 :     # Return the result.
1912 :     return @retVal;
1913 : parrello 1.6 }
1914 : parrello 1.1
1915 : parrello 1.7 =head3 GetAll
1916 :    
1917 : parrello 1.18 C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
1918 : parrello 1.7
1919 :     Return a list of values taken from the objects returned by a query. The first three
1920 :     parameters correspond to the parameters of the L</Get> method. The final parameter is
1921 :     a list of the fields desired from each record found by the query. The field name
1922 :     syntax is the standard syntax used for fields in the B<ERDB> system--
1923 :     B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
1924 :     or relationship and I<fieldName> is the name of the field.
1925 :    
1926 :     The list returned will be a list of lists. Each element of the list will contain
1927 :     the values returned for the fields specified in the fourth parameter. If one of the
1928 :     fields specified returns multiple values, they are flattened in with the rest. For
1929 :     example, the following call will return a list of the features in a particular
1930 :     spreadsheet cell, and each feature will be represented by a list containing the
1931 :     feature ID followed by all of its aliases.
1932 :    
1933 : parrello 1.18 C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
1934 : parrello 1.7
1935 :     =over 4
1936 :    
1937 :     =item objectNames
1938 :    
1939 :     List containing the names of the entity and relationship objects to be retrieved.
1940 :    
1941 :     =item filterClause
1942 :    
1943 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1944 :     be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1945 :     B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1946 :     parameter list as additional parameters. The fields in a filter clause can come from primary
1947 :     entity relations, relationship relations, or secondary entity relations; however, all of the
1948 :     entities and relationships involved must be included in the list of object names.
1949 :    
1950 :     =item parameterList
1951 :    
1952 :     List of the parameters to be substituted in for the parameters marks in the filter clause.
1953 :    
1954 :     =item fields
1955 :    
1956 :     List of the fields to be returned in each element of the list returned.
1957 :    
1958 :     =item count
1959 :    
1960 :     Maximum number of records to return. If omitted or 0, all available records will be returned.
1961 :    
1962 :     =item RETURN
1963 :    
1964 :     Returns a list of list references. Each element of the return list contains the values for the
1965 :     fields specified in the B<fields> parameter.
1966 :    
1967 :     =back
1968 :    
1969 :     =cut
1970 :     #: Return Type @@;
1971 :     sub GetAll {
1972 : parrello 1.10 # Get the parameters.
1973 :     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
1974 :     # Translate the parameters from a list reference to a list. If the parameter
1975 :     # list is a scalar we convert it into a singleton list.
1976 :     my @parmList = ();
1977 :     if (ref $parameterList eq "ARRAY") {
1978 : parrello 1.45 Trace("GetAll parm list is an array.") if T(4);
1979 : parrello 1.10 @parmList = @{$parameterList};
1980 :     } else {
1981 : parrello 1.45 Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
1982 : parrello 1.10 push @parmList, $parameterList;
1983 :     }
1984 : parrello 1.30 # Insure the counter has a value.
1985 :     if (!defined $count) {
1986 :     $count = 0;
1987 :     }
1988 :     # Add the row limit to the filter clause.
1989 :     if ($count > 0) {
1990 :     $filterClause .= " LIMIT $count";
1991 :     }
1992 : parrello 1.10 # Create the query.
1993 : parrello 1.45 my $query = $self->Get($objectNames, $filterClause, \@parmList);
1994 : parrello 1.10 # Set up a counter of the number of records read.
1995 :     my $fetched = 0;
1996 :     # Loop through the records returned, extracting the fields. Note that if the
1997 :     # counter is non-zero, we stop when the number of records read hits the count.
1998 :     my @retVal = ();
1999 :     while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
2000 :     my @rowData = $row->Values($fields);
2001 :     push @retVal, \@rowData;
2002 :     $fetched++;
2003 :     }
2004 :     # Return the resulting list.
2005 :     return @retVal;
2006 : parrello 1.7 }
2007 :    
2008 : parrello 1.18 =head3 EstimateRowSize
2009 :    
2010 :     C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
2011 :    
2012 :     Estimate the row size of the specified relation. The estimated row size is computed by adding
2013 :     up the average length for each data type.
2014 :    
2015 :     =over 4
2016 :    
2017 :     =item relName
2018 :    
2019 :     Name of the relation whose estimated row size is desired.
2020 :    
2021 :     =item RETURN
2022 :    
2023 :     Returns an estimate of the row size for the specified relation.
2024 :    
2025 :     =back
2026 :    
2027 :     =cut
2028 :     #: Return Type $;
2029 :     sub EstimateRowSize {
2030 :     # Get the parameters.
2031 :     my ($self, $relName) = @_;
2032 :     # Declare the return variable.
2033 :     my $retVal = 0;
2034 :     # Find the relation descriptor.
2035 :     my $relation = $self->_FindRelation($relName);
2036 :     # Get the list of fields.
2037 :     for my $fieldData (@{$relation->{Fields}}) {
2038 :     # Get the field type and add its length.
2039 :     my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
2040 :     $retVal += $fieldLen;
2041 :     }
2042 :     # Return the result.
2043 :     return $retVal;
2044 :     }
2045 :    
2046 : parrello 1.38 =head3 GetFieldTable
2047 :    
2048 :     C<< my $fieldHash = $self->GetFieldTable($objectnName); >>
2049 :    
2050 :     Get the field structure for a specified entity or relationship.
2051 :    
2052 :     =over 4
2053 :    
2054 :     =item objectName
2055 :    
2056 :     Name of the desired entity or relationship.
2057 :    
2058 :     =item RETURN
2059 :    
2060 :     The table containing the field descriptors for the specified object.
2061 :    
2062 :     =back
2063 :    
2064 :     =cut
2065 :    
2066 :     sub GetFieldTable {
2067 :     # Get the parameters.
2068 :     my ($self, $objectName) = @_;
2069 :     # Get the descriptor from the metadata.
2070 :     my $objectData = $self->_GetStructure($objectName);
2071 :     # Return the object's field table.
2072 :     return $objectData->{Fields};
2073 :     }
2074 :    
2075 :     =head3 GetUsefulCrossValues
2076 :    
2077 :     C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
2078 :    
2079 :     Return a list of the useful attributes that would be returned by a B<Cross> call
2080 :     from an entity of the source entity type through the specified relationship. This
2081 :     means it will return the fields of the target entity type and the intersection data
2082 :     fields in the relationship. Only primary table fields are returned. In other words,
2083 :     the field names returned will be for fields where there is always one and only one
2084 :     value.
2085 :    
2086 :     =over 4
2087 :    
2088 :     =item sourceEntity
2089 :    
2090 :     Name of the entity from which the relationship crossing will start.
2091 :    
2092 :     =item relationship
2093 :    
2094 :     Name of the relationship being crossed.
2095 :    
2096 :     =item RETURN
2097 :    
2098 :     Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.
2099 :    
2100 :     =back
2101 :    
2102 :     =cut
2103 :     #: Return Type @;
2104 :     sub GetUsefulCrossValues {
2105 :     # Get the parameters.
2106 :     my ($self, $sourceEntity, $relationship) = @_;
2107 :     # Declare the return variable.
2108 :     my @retVal = ();
2109 :     # Determine the target entity for the relationship. This is whichever entity is not
2110 :     # the source entity. So, if the source entity is the FROM, we'll get the name of
2111 :     # the TO, and vice versa.
2112 :     my $relStructure = $self->_GetStructure($relationship);
2113 :     my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");
2114 :     my $targetEntity = $relStructure->{$targetEntityType};
2115 :     # Get the field table for the entity.
2116 :     my $entityFields = $self->GetFieldTable($targetEntity);
2117 :     # The field table is a hash. The hash key is the field name. The hash value is a structure.
2118 :     # For the entity fields, the key aspect of the target structure is that the {relation} value
2119 :     # must match the entity name.
2120 :     my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }
2121 :     keys %{$entityFields};
2122 :     # Push the fields found onto the return variable.
2123 :     push @retVal, sort @fieldList;
2124 :     # Get the field table for the relationship.
2125 :     my $relationshipFields = $self->GetFieldTable($relationship);
2126 :     # Here we have a different rule. We want all the fields other than "from-link" and "to-link".
2127 :     # This may end up being an empty set.
2128 :     my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }
2129 :     keys %{$relationshipFields};
2130 :     # Push these onto the return list.
2131 :     push @retVal, sort @fieldList2;
2132 :     # Return the result.
2133 :     return @retVal;
2134 :     }
2135 :    
2136 : parrello 1.1 =head2 Internal Utility Methods
2137 :    
2138 : parrello 1.45 =head3 SetupSQL
2139 :    
2140 :     Process a list of object names and a filter clause so that they can be used to
2141 :     build an SQL statement. This method takes in a reference to a list of object names
2142 :     and a filter clause. It will return a corrected filter clause, a list of mapped
2143 :     names and the mapped name hash.
2144 :    
2145 :     This is an instance method.
2146 :    
2147 :     =over 4
2148 :    
2149 :     =item objectNames
2150 :    
2151 :     Reference to a list of the object names to be included in the query.
2152 :    
2153 :     =item filterClause
2154 :    
2155 :     A string containing the WHERE clause for the query (without the C<WHERE>) and also
2156 :     optionally the C<ORDER BY> and C<LIMIT> clauses.
2157 :    
2158 :     =item RETURN
2159 :    
2160 :     Returns a three-element list. The first element is the SQL statement suffix, beginning
2161 :     with the FROM clause. The second element is a reference to a list of the names to be
2162 :     used in retrieving the fields. The third element is a hash mapping the names to the
2163 :     objects they represent.
2164 :    
2165 :     =back
2166 :    
2167 :     =cut
2168 :    
2169 :     sub _SetupSQL {
2170 :     my ($self, $objectNames, $filterClause) = @_;
2171 :     # Adjust the list of object names to account for multiple occurrences of the
2172 :     # same object. We start with a hash table keyed on object name that will
2173 :     # return the object suffix. The first time an object is encountered it will
2174 :     # not be found in the hash. The next time the hash will map the object name
2175 :     # to 2, then 3, and so forth.
2176 :     my %objectHash = ();
2177 :     # This list will contain the object names as they are to appear in the
2178 :     # FROM list.
2179 :     my @fromList = ();
2180 :     # This list contains the suffixed object name for each object. It is exactly
2181 :     # parallel to the list in the $objectNames parameter.
2182 :     my @mappedNameList = ();
2183 :     # Finally, this hash translates from a mapped name to its original object name.
2184 :     my %mappedNameHash = ();
2185 :     # Now we create the lists. Note that for every single name we push something into
2186 :     # @fromList and @mappedNameList. This insures that those two arrays are exactly
2187 :     # parallel to $objectNames.
2188 :     for my $objectName (@{$objectNames}) {
2189 :     # Get the next suffix for this object.
2190 :     my $suffix = $objectHash{$objectName};
2191 :     if (! $suffix) {
2192 :     # Here we are seeing the object for the first time. The object name
2193 :     # is used as is.
2194 :     push @mappedNameList, $objectName;
2195 :     push @fromList, $objectName;
2196 :     $mappedNameHash{$objectName} = $objectName;
2197 :     # Denote the next suffix will be 2.
2198 :     $objectHash{$objectName} = 2;
2199 :     } else {
2200 :     # Here we've seen the object before. We construct a new name using
2201 :     # the suffix from the hash and update the hash.
2202 :     my $mappedName = "$objectName$suffix";
2203 :     $objectHash{$objectName} = $suffix + 1;
2204 :     # The FROM list has the object name followed by the mapped name. This
2205 :     # tells SQL it's still the same table, but we're using a different name
2206 :     # for it to avoid confusion.
2207 :     push @fromList, "$objectName $mappedName";
2208 :     # The mapped-name list contains the real mapped name.
2209 :     push @mappedNameList, $mappedName;
2210 :     # Finally, enable us to get back from the mapped name to the object name.
2211 :     $mappedNameHash{$mappedName} = $objectName;
2212 :     }
2213 :     }
2214 :     # Begin the SELECT suffix. It starts with
2215 :     #
2216 :     # FROM name1, name2, ... nameN
2217 :     #
2218 :     my $suffix = "FROM " . join(', ', @fromList);
2219 :     # Check for a filter clause.
2220 :     if ($filterClause) {
2221 :     # Here we have one, so we convert its field names and add it to the query. First,
2222 :     # We create a copy of the filter string we can work with.
2223 :     my $filterString = $filterClause;
2224 :     # Next, we sort the object names by length. This helps protect us from finding
2225 :     # object names inside other object names when we're doing our search and replace.
2226 :     my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2227 :     # We will also keep a list of conditions to add to the WHERE clause in order to link
2228 :     # entities and relationships as well as primary relations to secondary ones.
2229 :     my @joinWhere = ();
2230 :     # The final preparatory step is to create a hash table of relation names. The
2231 :     # table begins with the relation names already in the SELECT command. We may
2232 :     # need to add relations later if there is filtering on a field in a secondary
2233 :     # relation. The secondary relations are the ones that contain multiply-
2234 :     # occurring or optional fields.
2235 :     my %fromNames = map { $_ => 1 } @sortedNames;
2236 :     # We are ready to begin. We loop through the object names, replacing each
2237 :     # object name's field references by the corresponding SQL field reference.
2238 :     # Along the way, if we find a secondary relation, we will need to add it
2239 :     # to the FROM clause.
2240 :     for my $mappedName (@sortedNames) {
2241 :     # Get the length of the object name plus 2. This is the value we add to the
2242 :     # size of the field name to determine the size of the field reference as a
2243 :     # whole.
2244 :     my $nameLength = 2 + length $mappedName;
2245 :     # Get the real object name for this mapped name.
2246 :     my $objectName = $mappedNameHash{$mappedName};
2247 :     Trace("Processing $mappedName for object $objectName.") if T(4);
2248 :     # Get the object's field list.
2249 :     my $fieldList = $self->GetFieldTable($objectName);
2250 :     # Find the field references for this object.
2251 :     while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2252 :     # At this point, $1 contains the field name, and the current position
2253 :     # is set immediately after the final parenthesis. We pull out the name of
2254 :     # the field and the position and length of the field reference as a whole.
2255 :     my $fieldName = $1;
2256 :     my $len = $nameLength + length $fieldName;
2257 :     my $pos = pos($filterString) - $len;
2258 :     # Insure the field exists.
2259 :     if (!exists $fieldList->{$fieldName}) {
2260 :     Confess("Field $fieldName not found for object $objectName.");
2261 :     } else {
2262 :     Trace("Processing $fieldName at position $pos.") if T(4);
2263 :     # Get the field's relation.
2264 :     my $relationName = $fieldList->{$fieldName}->{relation};
2265 :     # Now we have a secondary relation. We need to insure it matches the
2266 :     # mapped name of the primary relation. First we peel off the suffix
2267 :     # from the mapped name.
2268 :     my $mappingSuffix = substr $mappedName, length($objectName);
2269 :     # Put the mapping suffix onto the relation name to get the
2270 :     # mapped relation name.
2271 :     my $mappedRelationName = "$relationName$mappingSuffix";
2272 :     # Insure the relation is in the FROM clause.
2273 :     if (!exists $fromNames{$mappedRelationName}) {
2274 :     # Add the relation to the FROM clause.
2275 :     if ($mappedRelationName eq $relationName) {
2276 :     # The name is un-mapped, so we add it without
2277 :     # any frills.
2278 :     $suffix .= ", $relationName";
2279 :     push @joinWhere, "$objectName.id = $relationName.id";
2280 :     } else {
2281 :     # Here we have a mapping situation.
2282 :     $suffix .= ", $relationName $mappedRelationName";
2283 :     push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2284 :     }
2285 :     # Denote we have this relation available for future fields.
2286 :     $fromNames{$mappedRelationName} = 1;
2287 :     }
2288 :     # Form an SQL field reference from the relation name and the field name.
2289 :     my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2290 :     # Put it into the filter string in place of the old value.
2291 :     substr($filterString, $pos, $len) = $sqlReference;
2292 :     # Reposition the search.
2293 :     pos $filterString = $pos + length $sqlReference;
2294 :     }
2295 :     }
2296 :     }
2297 :     # The next step is to join the objects together. We only need to do this if there
2298 :     # is more than one object in the object list. We start with the first object and
2299 :     # run through the objects after it. Note also that we make a safety copy of the
2300 :     # list before running through it.
2301 :     my @mappedObjectList = @mappedNameList;
2302 :     my $lastMappedObject = shift @mappedObjectList;
2303 :     # Get the join table.
2304 :     my $joinTable = $self->{_metaData}->{Joins};
2305 :     # Loop through the object list.
2306 :     for my $thisMappedObject (@mappedObjectList) {
2307 :     # Look for a join using the real object names.
2308 :     my $lastObject = $mappedNameHash{$lastMappedObject};
2309 :     my $thisObject = $mappedNameHash{$thisMappedObject};
2310 :     my $joinKey = "$lastObject/$thisObject";
2311 :     if (!exists $joinTable->{$joinKey}) {
2312 :     # Here there's no join, so we throw an error.
2313 :     Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2314 :     } else {
2315 :     # Get the join clause.
2316 :     my $unMappedJoin = $joinTable->{$joinKey};
2317 :     # Fix the names.
2318 :     $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2319 :     $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2320 :     push @joinWhere, $unMappedJoin;
2321 :     # Save this object as the last object for the next iteration.
2322 :     $lastMappedObject = $thisMappedObject;
2323 :     }
2324 :     }
2325 :     # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2326 :     # here is we want the filter clause to be empty if there's no WHERE filter.
2327 :     # We'll put the ORDER BY / LIMIT clauses in the following variable.
2328 :     my $orderClause = "";
2329 :     # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2330 :     # operator so that we find the first occurrence of either verb.
2331 :     if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2332 :     # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2333 :     my $pos = pos $filterString;
2334 :     $orderClause = $2 . substr($filterString, $pos);
2335 :     $filterString = $1;
2336 :     }
2337 :     # Add the filter and the join clauses (if any) to the SELECT command.
2338 :     if ($filterString) {
2339 :     Trace("Filter string is \"$filterString\".") if T(4);
2340 :     push @joinWhere, "($filterString)";
2341 :     }
2342 :     if (@joinWhere) {
2343 :     $suffix .= " WHERE " . join(' AND ', @joinWhere);
2344 :     }
2345 :     # Add the sort or limit clause (if any) to the SELECT command.
2346 :     if ($orderClause) {
2347 :     $suffix .= " $orderClause";
2348 :     }
2349 :     }
2350 :     # Return the suffix, the mapped name list, and the mapped name hash.
2351 :     return ($suffix, \@mappedNameList, \%mappedNameHash);
2352 :     }
2353 :    
2354 :     =head3 GetStatementHandle
2355 :    
2356 :     This method will prepare and execute an SQL query, returning the statement handle.
2357 :     The main reason for doing this here is so that everybody who does SQL queries gets
2358 :     the benefit of tracing.
2359 :    
2360 :     This is an instance method.
2361 :    
2362 :     =over 4
2363 :    
2364 :     =item command
2365 :    
2366 :     Command to prepare and execute.
2367 :    
2368 :     =item params
2369 :    
2370 :     Reference to a list of the values to be substituted in for the parameter marks.
2371 :    
2372 :     =item RETURN
2373 :    
2374 :     Returns a prepared and executed statement handle from which the caller can extract
2375 :     results.
2376 :    
2377 :     =back
2378 :    
2379 :     =cut
2380 :    
2381 :     sub _GetStatementHandle {
2382 :     # Get the parameters.
2383 :     my ($self, $command, $params) = @_;
2384 :     # Trace the query.
2385 :     Trace("SQL query: $command") if T(SQL => 3);
2386 :     Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2387 :     # Get the database handle.
2388 :     my $dbh = $self->{_dbh};
2389 :     # Prepare the command.
2390 :     my $sth = $dbh->prepare_command($command);
2391 :     # Execute it with the parameters bound in.
2392 :     $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2393 :     # Return the statement handle.
2394 :     return $sth;
2395 :     }
2396 :    
2397 : parrello 1.1 =head3 GetLoadStats
2398 :    
2399 :     Return a blank statistics object for use by the load methods.
2400 :    
2401 :     This is a static method.
2402 :    
2403 :     =cut
2404 :    
2405 : parrello 1.29 sub _GetLoadStats{
2406 : parrello 1.28 return Stats->new();
2407 : parrello 1.1 }
2408 :    
2409 :     =head3 GenerateFields
2410 :    
2411 :     Generate field values from a field structure and store in a specified table. The field names
2412 :     are first sorted by pass count, certain pre-defined fields are removed from the list, and
2413 :     then we rip through them evaluation the data generation string. Fields in the primary relation
2414 :     are stored as scalars; fields in secondary relations are stored as value lists.
2415 :    
2416 :     This is a static method.
2417 :    
2418 :     =over 4
2419 :    
2420 :     =item this
2421 :    
2422 :     Hash table into which the field values should be placed.
2423 :    
2424 :     =item fields
2425 :    
2426 :     Field structure from which the field descriptors should be taken.
2427 :    
2428 :     =item type
2429 :    
2430 :     Type name of the object whose fields are being generated.
2431 :    
2432 :     =item values (optional)
2433 :    
2434 :     Reference to a value structure from which additional values can be taken.
2435 :    
2436 :     =item from (optiona)
2437 :    
2438 :     Reference to the source entity instance if relationship data is being generated.
2439 :    
2440 :     =item to (optional)
2441 :    
2442 :     Reference to the target entity instance if relationship data is being generated.
2443 :    
2444 :     =back
2445 :    
2446 :     =cut
2447 :    
2448 :     sub _GenerateFields {
2449 : parrello 1.10 # Get the parameters.
2450 :     my ($this, $fields, $type, $values, $from, $to) = @_;
2451 :     # Sort the field names by pass number.
2452 :     my @fieldNames = sort { $fields->{$a}->{DataGen}->{pass} <=> $fields->{$b}->{DataGen}->{pass} } keys %{$fields};
2453 :     # Loop through the field names, generating data.
2454 :     for my $name (@fieldNames) {
2455 :     # Only proceed if this field needs to be generated.
2456 :     if (!exists $this->{$name}) {
2457 :     # Get this field's data generation descriptor.
2458 :     my $fieldDescriptor = $fields->{$name};
2459 :     my $data = $fieldDescriptor->{DataGen};
2460 :     # Get the code to generate the field value.
2461 :     my $codeString = $data->{content};
2462 :     # Determine whether or not this field is in the primary relation.
2463 :     if ($fieldDescriptor->{relation} eq $type) {
2464 :     # Here we have a primary relation field. Store the field value as
2465 :     # a scalar.
2466 :     $this->{$name} = eval($codeString);
2467 :     } else {
2468 :     # Here we have a secondary relation field. Create a null list
2469 :     # and push the desired number of field values onto it.
2470 :     my @fieldValues = ();
2471 :     my $count = IntGen(0,$data->{testCount});
2472 :     for (my $i = 0; $i < $count; $i++) {
2473 :     my $newValue = eval($codeString);
2474 :     push @fieldValues, $newValue;
2475 :     }
2476 :     # Store the value list in the main hash.
2477 :     $this->{$name} = \@fieldValues;
2478 :     }
2479 :     }
2480 :     }
2481 : parrello 1.1 }
2482 :    
2483 :     =head3 DumpRelation
2484 :    
2485 :     Dump the specified relation's to the specified output file in tab-delimited format.
2486 :    
2487 :     This is an instance method.
2488 :    
2489 :     =over 4
2490 :    
2491 :     =item outputDirectory
2492 :    
2493 :     Directory to contain the output file.
2494 :    
2495 :     =item relationName
2496 :    
2497 :     Name of the relation to dump.
2498 :    
2499 :     =item relation
2500 :    
2501 :     Structure describing the relation to be dumped.
2502 :    
2503 :     =back
2504 :    
2505 :     =cut
2506 :    
2507 :     sub _DumpRelation {
2508 : parrello 1.10 # Get the parameters.
2509 :     my ($self, $outputDirectory, $relationName, $relation) = @_;
2510 :     # Open the output file.
2511 :     my $fileName = "$outputDirectory/$relationName.dtx";
2512 :     open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
2513 :     # Create a query for the specified relation.
2514 :     my $dbh = $self->{_dbh};
2515 :     my $query = $dbh->prepare_command("SELECT * FROM $relationName");
2516 :     # Execute the query.
2517 :     $query->execute() || Confess("SELECT error dumping $relationName.");
2518 :     # Loop through the results.
2519 :     while (my @row = $query->fetchrow) {
2520 :     # Escape any tabs or new-lines in the row text.
2521 :     for my $field (@row) {
2522 :     $field =~ s/\n/\\n/g;
2523 :     $field =~ s/\t/\\t/g;
2524 :     }
2525 :     # Tab-join the row and write it to the output file.
2526 :     my $rowText = join("\t", @row);
2527 :     print DTXOUT "$rowText\n";
2528 :     }
2529 :     # Close the output file.
2530 :     close DTXOUT;
2531 : parrello 1.1 }
2532 :    
2533 :     =head3 GetStructure
2534 :    
2535 :     Get the data structure for a specified entity or relationship.
2536 :    
2537 :     This is an instance method.
2538 :    
2539 :     =over 4
2540 :    
2541 :     =item objectName
2542 :    
2543 :     Name of the desired entity or relationship.
2544 :    
2545 :     =item RETURN
2546 :    
2547 :     The descriptor for the specified object.
2548 :    
2549 :     =back
2550 :    
2551 :     =cut
2552 :    
2553 :     sub _GetStructure {
2554 : parrello 1.10 # Get the parameters.
2555 :     my ($self, $objectName) = @_;
2556 :     # Get the metadata structure.
2557 :     my $metadata = $self->{_metaData};
2558 :     # Declare the variable to receive the descriptor.
2559 :     my $retVal;
2560 :     # Get the descriptor from the metadata.
2561 :     if (exists $metadata->{Entities}->{$objectName}) {
2562 :     $retVal = $metadata->{Entities}->{$objectName};
2563 :     } elsif (exists $metadata->{Relationships}->{$objectName}) {
2564 :     $retVal = $metadata->{Relationships}->{$objectName};
2565 :     } else {
2566 :     Confess("Object $objectName not found in database.");
2567 :     }
2568 :     # Return the descriptor.
2569 :     return $retVal;
2570 : parrello 1.1 }
2571 :    
2572 :     =head3 GetRelationTable
2573 :    
2574 :     Get the list of relations for a specified entity or relationship.
2575 :    
2576 :     This is an instance method.
2577 :    
2578 :     =over 4
2579 :    
2580 :     =item objectName
2581 :    
2582 :     Name of the desired entity or relationship.
2583 :    
2584 :     =item RETURN
2585 :    
2586 :     A table containing the relations for the specified object.
2587 :    
2588 :     =back
2589 :    
2590 :     =cut
2591 :    
2592 :     sub _GetRelationTable {
2593 : parrello 1.10 # Get the parameters.
2594 :     my ($self, $objectName) = @_;
2595 :     # Get the descriptor from the metadata.
2596 :     my $objectData = $self->_GetStructure($objectName);
2597 :     # Return the object's relation list.
2598 :     return $objectData->{Relations};
2599 : parrello 1.1 }
2600 :    
2601 :     =head3 ValidateFieldNames
2602 :    
2603 :     Determine whether or not the field names are valid. A description of the problems with the names
2604 :     will be written to the standard error output. If there is an error, this method will abort. This is
2605 :     a static method.
2606 :    
2607 :     =over 4
2608 :    
2609 :     =item metadata
2610 :    
2611 :     Metadata structure loaded from the XML data definition.
2612 :    
2613 :     =back
2614 :    
2615 :     =cut
2616 :    
2617 :     sub _ValidateFieldNames {
2618 : parrello 1.10 # Get the object.
2619 :     my ($metadata) = @_;
2620 :     # Declare the return value. We assume success.
2621 :     my $retVal = 1;
2622 :     # Loop through the sections of the database definition.
2623 :     for my $section ('Entities', 'Relationships') {
2624 :     # Loop through the objects in this section.
2625 :     for my $object (values %{$metadata->{$section}}) {
2626 :     # Loop through the object's fields.
2627 :     for my $fieldName (keys %{$object->{Fields}}) {
2628 :     # Now we make some initial validations.
2629 :     if ($fieldName =~ /--/) {
2630 :     # Here we have a doubled minus sign.
2631 :     print STDERR "Field name $fieldName has a doubled hyphen.\n";
2632 :     $retVal = 0;
2633 :     } elsif ($fieldName !~ /^[A-Za-z]/) {
2634 :     # Here the field name is missing the initial letter.
2635 :     print STDERR "Field name $fieldName does not begin with a letter.\n";
2636 :     $retVal = 0;
2637 :     } else {
2638 :     # Strip out the minus signs. Everything remaining must be a letter
2639 :     # or digit.
2640 :     my $strippedName = $fieldName;
2641 :     $strippedName =~ s/-//g;
2642 :     if ($strippedName !~ /^[A-Za-z0-9]+$/) {
2643 :     print STDERR "Field name $fieldName contains illegal characters.\n";
2644 :     $retVal = 0;
2645 :     }
2646 :     }
2647 :     }
2648 :     }
2649 :     }
2650 :     # If an error was found, fail.
2651 :     if ($retVal == 0) {
2652 :     Confess("Errors found in field names.");
2653 :     }
2654 : parrello 1.1 }
2655 :    
2656 :     =head3 LoadRelation
2657 :    
2658 :     Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk
2659 :     file with the same name as the relation exists in the specified directory.
2660 :    
2661 :     This is an instance method.
2662 :    
2663 :     =over 4
2664 :    
2665 :     =item dbh
2666 :    
2667 :     DBKernel object for accessing the database.
2668 :    
2669 :     =item directoryName
2670 :    
2671 :     Name of the directory containing the tab-delimited data files.
2672 :    
2673 :     =item relationName
2674 :    
2675 :     Name of the relation to load.
2676 :    
2677 :     =item rebuild
2678 :    
2679 :     TRUE if the table should be dropped and re-created before loading.
2680 :    
2681 :     =item RETURN
2682 :    
2683 :     Returns a statistical object describing the number of records read and a list of error messages.
2684 :    
2685 :     =back
2686 :    
2687 :     =cut
2688 :    
2689 :     sub _LoadRelation {
2690 : parrello 1.10 # Get the parameters.
2691 :     my ($self, $directoryName, $relationName, $rebuild) = @_;
2692 :     # Create the file name.
2693 :     my $fileName = "$directoryName/$relationName";
2694 :     # If the file doesn't exist, try adding the .dtx suffix.
2695 :     if (! -e $fileName) {
2696 :     $fileName .= ".dtx";
2697 :     if (! -e $fileName) {
2698 :     $fileName = "";
2699 :     }
2700 :     }
2701 :     # Create the return object.
2702 :     my $retVal = _GetLoadStats();
2703 :     # If a file exists to load the table, its name will be in $fileName. Otherwise, $fileName will
2704 :     # be a null string.
2705 :     if ($fileName ne "") {
2706 :     # Load the relation from the file.
2707 :     $retVal = $self->LoadTable($fileName, $relationName, $rebuild);
2708 :     } elsif ($rebuild) {
2709 :     # Here we are rebuilding, but no file exists, so we just re-create the table.
2710 :     $self->CreateTable($relationName, 1);
2711 :     }
2712 :     # Return the statistics from the load.
2713 :     return $retVal;
2714 : parrello 1.1 }
2715 :    
2716 :     =head3 LoadMetaData
2717 :    
2718 :     This method loads the data describing this database from an XML file into a metadata structure.
2719 :     The resulting structure is a set of nested hash tables containing all the information needed to
2720 :     load or use the database. The schema for the XML file is F<ERDatabase.xml>.
2721 :    
2722 :     This is a static method.
2723 :    
2724 :     =over 4
2725 :    
2726 :     =item filename
2727 :    
2728 :     Name of the file containing the database definition.
2729 :    
2730 :     =item RETURN
2731 :    
2732 :     Returns a structure describing the database.
2733 :    
2734 :     =back
2735 :    
2736 :     =cut
2737 :    
2738 :     sub _LoadMetaData {
2739 : parrello 1.10 # Get the parameters.
2740 :     my ($filename) = @_;
2741 : parrello 1.15 Trace("Reading Sprout DBD from $filename.") if T(2);
2742 : parrello 1.10 # Slurp the XML file into a variable. Extensive use of options is used to insure we
2743 :     # get the exact structure we want.
2744 :     my $metadata = XML::Simple::XMLin($filename,
2745 :     GroupTags => { Relationships => 'Relationship',
2746 :     Entities => 'Entity',
2747 :     Fields => 'Field',
2748 :     Indexes => 'Index',
2749 :     IndexFields => 'IndexField'},
2750 :     KeyAttr => { Relationship => 'name',
2751 :     Entity => 'name',
2752 :     Field => 'name'},
2753 :     ForceArray => ['Field', 'Index', 'IndexField'],
2754 :     ForceContent => 1,
2755 :     NormalizeSpace => 2
2756 :     );
2757 :     Trace("XML metadata loaded from file $filename.") if T(1);
2758 :     # Before we go any farther, we need to validate the field and object names. If an error is found,
2759 :     # the method below will fail.
2760 :     _ValidateFieldNames($metadata);
2761 :     # Next we need to create a hash table for finding relations. The entities and relationships are
2762 :     # implemented as one or more database relations.
2763 :     my %masterRelationTable = ();
2764 :     # Loop through the entities.
2765 :     my $entityList = $metadata->{Entities};
2766 :     for my $entityName (keys %{$entityList}) {
2767 :     my $entityStructure = $entityList->{$entityName};
2768 :     #
2769 : parrello 1.12 # The first step is to create all the entity's default values. For C<Field> elements,
2770 : parrello 1.10 # the relation name must be added where it is not specified. For relationships,
2771 :     # the B<from-link> and B<to-link> fields must be inserted, and for entities an B<id>
2772 :     # field must be added to each relation. Finally, each field will have a C<PrettySort> attribute
2773 :     # added that can be used to pull the implicit fields to the top when displaying the field
2774 :     # documentation. The PrettySort values are 1-based and indicate in which pass through a
2775 :     # relation's data the field should be displayed-- 1 for the first pass, 2 for the second,
2776 :     # and so on.
2777 :     #
2778 :     # Fix up this entity.
2779 :     _FixupFields($entityStructure, $entityName, 2, 3);
2780 :     # Add the ID field.
2781 :     _AddField($entityStructure, 'id', { type => $entityStructure->{keyType},
2782 :     relation => $entityName,
2783 :     Notes => { content => "Unique identifier for this \[b\]$entityName\[/b\]." },
2784 :     PrettySort => 1});
2785 :     #
2786 :     # The current field list enables us to quickly find the relation containing a particular field.
2787 :     # We also need a list that tells us the fields in each relation. We do this by creating a
2788 :     # Relations structure in the entity structure and collating the fields into it based on their
2789 :     # C<relation> property. There is one tricky bit, which is that every relation has to have the
2790 :     # C<id> field in it. Note also that the field list is put into a C<Fields> member of the
2791 :     # relation's structure so that it looks more like the entity and relationship structures.
2792 :     #
2793 :     # First we need to create the relations list.
2794 :     my $relationTable = { };
2795 :     # Loop through the fields. We use a list of field names to prevent a problem with
2796 :     # the hash table cursor losing its place during the loop.
2797 :     my $fieldList = $entityStructure->{Fields};
2798 :     my @fieldNames = keys %{$fieldList};
2799 :     for my $fieldName (@fieldNames) {
2800 :     my $fieldData = $fieldList->{$fieldName};
2801 :     # Get the current field's relation name.
2802 :     my $relationName = $fieldData->{relation};
2803 :     # Insure the relation exists.
2804 :     if (!exists $relationTable->{$relationName}) {
2805 :     $relationTable->{$relationName} = { Fields => { } };
2806 :     }
2807 :     # Add the field to the relation's field structure.
2808 :     $relationTable->{$relationName}->{Fields}->{$fieldName} = $fieldData;
2809 :     }
2810 :     # Now that we've organized all our fields by relation name we need to do some serious
2811 :     # housekeeping. We must add the C<id> field to every relation and convert each relation
2812 :     # to a list of fields. First, we need the ID field itself.
2813 :     my $idField = $fieldList->{id};
2814 :     # Loop through the relations.
2815 :     for my $relationName (keys %{$relationTable}) {
2816 :     my $relation = $relationTable->{$relationName};
2817 :     # Get the relation's field list.
2818 :     my $relationFieldList = $relation->{Fields};
2819 :     # Add the ID field to it. If the field's already there, it will not make any
2820 :     # difference.
2821 :     $relationFieldList->{id} = $idField;
2822 :     # Convert the field set from a hash into a list using the pretty-sort number.
2823 :     $relation->{Fields} = _ReOrderRelationTable($relationFieldList);
2824 :     # Add the relation to the master table.
2825 :     $masterRelationTable{$relationName} = $relation;
2826 :     }
2827 :     # The indexes come next. The primary relation will have a unique-keyed index based on the ID field.
2828 :     # The other relations must have at least one index that begins with the ID field. In addition, the
2829 :     # metadata may require alternate indexes. We do those alternate indexes first. To begin, we need to
2830 :     # get the entity's field list and index list.
2831 :     my $indexList = $entityStructure->{Indexes};
2832 :     # Loop through the indexes.
2833 :     for my $indexData (@{$indexList}) {
2834 :     # We need to find this index's fields. All of them should belong to the same relation.
2835 :     # The ID field is an exception, since it's in all relations.
2836 :     my $relationName = '0';
2837 :     for my $fieldDescriptor (@{$indexData->{IndexFields}}) {
2838 :     # Get this field's name.
2839 :     my $fieldName = $fieldDescriptor->{name};
2840 :     # Only proceed if it is NOT the ID field.
2841 :     if ($fieldName ne 'id') {
2842 :     # Find the relation containing the current index field.
2843 :     my $thisName = $fieldList->{$fieldName}->{relation};
2844 :     if ($relationName eq '0') {
2845 :     # Here we're looking at the first field, so we save its relation name.
2846 :     $relationName = $thisName;
2847 :     } elsif ($relationName ne $thisName) {
2848 :     # Here we have a field mismatch.
2849 :     Confess("Mixed index: field $fieldName does not belong to relation $relationName.");
2850 :     }
2851 :     }
2852 :     }
2853 :     # Now $relationName is the name of the relation that contains this index. Add the index structure
2854 :     # to the relation.
2855 :     push @{$relationTable->{$relationName}->{Indexes}}, $indexData;
2856 :     }
2857 :     # Now each index has been put in a relation. We need to add the primary index for the primary
2858 :     # relation.
2859 :     push @{$relationTable->{$entityName}->{Indexes}},
2860 :     { IndexFields => [ {name => 'id', order => 'ascending'} ], Unique => 'true',
2861 :     Notes => { content => "Primary index for $entityName." }
2862 :     };
2863 :     # The next step is to insure that each relation has at least one index that begins with the ID field.
2864 :     # After that, we convert each relation's index list to an index table. We first need to loop through
2865 :     # the relations.
2866 :     for my $relationName (keys %{$relationTable}) {
2867 :     my $relation = $relationTable->{$relationName};
2868 :     # Get the relation's index list.
2869 :     my $indexList = $relation->{Indexes};
2870 :     # Insure this relation has an ID index.
2871 :     my $found = 0;
2872 :     for my $index (@{$indexList}) {
2873 :     if ($index->{IndexFields}->[0]->{name} eq "id") {
2874 :     $found = 1;
2875 :     }
2876 :     }
2877 :     if ($found == 0) {
2878 :     push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
2879 :     }
2880 :     # Now we need to convert the relation's index list to an index table. We begin by creating
2881 :     # an empty table in the relation structure.
2882 :     $relation->{Indexes} = { };
2883 :     # Loop through the indexes.
2884 :     my $count = 0;
2885 :     for my $index (@{$indexList}) {
2886 :     # Add this index to the index table.
2887 :     _AddIndex("idx$relationName$count", $relation, $index);
2888 :     # Increment the counter so that the next index has a different name.
2889 :     $count++;
2890 :     }
2891 :     }
2892 :     # Finally, we add the relation structure to the entity.
2893 :     $entityStructure->{Relations} = $relationTable;
2894 :     }
2895 :     # Loop through the relationships. Relationships actually turn out to be much simpler than entities.
2896 :     # For one thing, there is only a single constituent relation.
2897 :     my $relationshipList = $metadata->{Relationships};
2898 :     for my $relationshipName (keys %{$relationshipList}) {
2899 :     my $relationshipStructure = $relationshipList->{$relationshipName};
2900 :     # Fix up this relationship.
2901 :     _FixupFields($relationshipStructure, $relationshipName, 2, 3);
2902 :     # Format a description for the FROM field.
2903 :     my $fromEntity = $relationshipStructure->{from};
2904 :     my $fromComment = "<b>id</b> of the source <b><a href=\"#$fromEntity\">$fromEntity</a></b>.";
2905 :     # Get the FROM entity's key type.
2906 :     my $fromType = $entityList->{$fromEntity}->{keyType};
2907 :     # Add the FROM field.
2908 :     _AddField($relationshipStructure, 'from-link', { type => $fromType,
2909 :     relation => $relationshipName,
2910 :     Notes => { content => $fromComment },
2911 :     PrettySort => 1});
2912 :     # Format a description for the TO field.
2913 :     my $toEntity = $relationshipStructure->{to};
2914 :     my $toComment = "<b>id</b> of the target <b><a href=\"#$toEntity\">$toEntity</a></b>.";
2915 :     # Get the TO entity's key type.
2916 :     my $toType = $entityList->{$toEntity}->{keyType};
2917 :     # Add the TO field.
2918 :     _AddField($relationshipStructure, 'to-link', { type=> $toType,
2919 :     relation => $relationshipName,
2920 :     Notes => { content => $toComment },
2921 :     PrettySort => 1});
2922 :     # Create an index-free relation from the fields.
2923 :     my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
2924 :     Indexes => { } };
2925 :     $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
2926 :     # Create the FROM and TO indexes.
2927 :     _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
2928 :     _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
2929 :     # Add the relation to the master table.
2930 :     $masterRelationTable{$relationshipName} = $thisRelation;
2931 :     }
2932 :     # Now store the master relation table in the metadata structure.
2933 :     $metadata->{RelationTable} = \%masterRelationTable;
2934 :     # Our final task is to create the join table. The join table is a hash that describes all
2935 :     # the join clauses for traveling through the relationships. The join clause is an equality
2936 :     # condition that can be put into a WHERE clause in order to join two objects. Two relationships
2937 :     # can be joined if they share an entity in common; and an entity can be joined to a relationship
2938 :     # if the entity is at either end of the relationship.
2939 :     my %joinTable = ();
2940 :     # Loop through the entities.
2941 :     for my $entityName (keys %{$entityList}) {
2942 :     # Build three lists of the relationships connected to this entity. One will be
2943 :     # for relationships from the entity, one for relationships to the entity, and
2944 :     # one for recursive relationships.
2945 :     my @fromList = ();
2946 :     my @toList = ();
2947 :     my @bothList = ();
2948 : parrello 1.21 Trace("Join table build for $entityName.") if T(metadata => 4);
2949 : parrello 1.10 for my $relationshipName (keys %{$relationshipList}) {
2950 :     my $relationship = $relationshipList->{$relationshipName};
2951 :     # Determine if this relationship has our entity in one of its link fields.
2952 :     my $fromEntity = $relationship->{from};
2953 :     my $toEntity = $relationship->{to};
2954 : parrello 1.41 Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(Joins => 4);
2955 : parrello 1.10 if ($fromEntity eq $entityName) {
2956 :     if ($toEntity eq $entityName) {
2957 :     # Here the relationship is recursive.
2958 :     push @bothList, $relationshipName;
2959 : parrello 1.21 Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
2960 : parrello 1.10 } else {
2961 :     # Here the relationship comes from the entity.
2962 :     push @fromList, $relationshipName;
2963 : parrello 1.21 Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
2964 : parrello 1.10 }
2965 :     } elsif ($toEntity eq $entityName) {
2966 :     # Here the relationship goes to the entity.
2967 :     push @toList, $relationshipName;
2968 : parrello 1.21 Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
2969 : parrello 1.10 }
2970 :     }
2971 :     # Create the nonrecursive joins. Note that we build two hashes for running
2972 :     # through the nonrecursive relationships since we'll have an outer loop
2973 :     # and an inner loop, and we can't do two "each" iterations on the same
2974 :     # hash table at the same time.
2975 :     my %directRelationships = ( from => \@fromList, to => \@toList );
2976 :     my %otherRelationships = ( from => \@fromList, to => \@toList );
2977 :     for my $linkType (keys %directRelationships) {
2978 :     my $relationships = $directRelationships{$linkType};
2979 :     # Loop through all the relationships.
2980 :     for my $relationshipName (@{$relationships}) {
2981 :     # Create joins between the entity and this relationship.
2982 :     my $linkField = "$relationshipName.${linkType}_link";
2983 :     my $joinClause = "$entityName.id = $linkField";
2984 : parrello 1.21 Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4);
2985 : parrello 1.10 $joinTable{"$entityName/$relationshipName"} = $joinClause;
2986 :     $joinTable{"$relationshipName/$entityName"} = $joinClause;
2987 :     # Create joins between this relationship and the other relationships.
2988 :     for my $otherType (keys %otherRelationships) {
2989 :     my $otherships = $otherRelationships{$otherType};
2990 :     for my $otherName (@{$otherships}) {
2991 :     # Get the key for this join.
2992 :     my $joinKey = "$otherName/$relationshipName";
2993 :     # Check for a duplicate or a self-join.
2994 :     if (exists $joinTable{$joinKey}) {
2995 :     # Here we have a duplicate, which means that the join
2996 :     # path is ambiguous. We delete the join from the join
2997 :     # table to prevent it from being used.
2998 :     delete $joinTable{$joinKey};
2999 :     Trace("Deleting ambiguous join $joinKey.") if T(4);
3000 :     } elsif ($otherName ne $relationshipName) {
3001 :     # Here we have a valid join. Note that joins between a
3002 :     # relationship and itself are prohibited.
3003 :     my $relJoinClause = "$otherName.${otherType}_link = $linkField";
3004 :     $joinTable{$joinKey} = $relJoinClause;
3005 : parrello 1.21 Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
3006 : parrello 1.10 }
3007 :     }
3008 :     }
3009 :     # Create joins between this relationship and the recursive relationships.
3010 :     # We don't need to check for ambiguous joins here, because a recursive
3011 :     # relationship can only be ambiguous with another recursive relationship,
3012 :     # and the incoming relationship from the outer loop is never recursive.
3013 :     for my $otherName (@bothList) {
3014 : parrello 1.21 Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4);
3015 : parrello 1.10 # Join from the left.
3016 :     $joinTable{"$relationshipName/$otherName"} =
3017 :     "$linkField = $otherName.from_link";
3018 :     # Join from the right.
3019 :     $joinTable{"$otherName/$relationshipName"} =
3020 :     "$otherName.to_link = $linkField";
3021 :     }
3022 :     }
3023 :     }
3024 :     # Create entity joins for the recursive relationships. Unlike the non-recursive
3025 :     # joins, the direction makes a difference with the recursive joins. This can give
3026 :     # rise to situations where we can't create the path we want; however, it is always
3027 :     # possible to get the same effect using multiple queries.
3028 :     for my $relationshipName (@bothList) {
3029 : parrello 1.21 Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
3030 : parrello 1.10 # Join to the entity from each direction.
3031 :     $joinTable{"$entityName/$relationshipName"} =
3032 :     "$entityName.id = $relationshipName.from_link";
3033 :     $joinTable{"$relationshipName/$entityName"} =
3034 :     "$relationshipName.to_link = $entityName.id";
3035 :     }
3036 :     }
3037 :     # Add the join table to the structure.
3038 :     $metadata->{Joins} = \%joinTable;
3039 :     # Return the slurped and fixed-up structure.
3040 :     return $metadata;
3041 : parrello 1.1 }
3042 :    
3043 : parrello 1.42 =head3 SortNeeded
3044 :    
3045 :     C<< my $flag = $erdb->SortNeeded($relationName); >>
3046 :    
3047 :     Return TRUE if the specified relation should be sorted during loading to remove duplicate keys,
3048 :     else FALSE.
3049 :    
3050 :     =over 4
3051 :    
3052 :     =item relationName
3053 :    
3054 :     Name of the relation to be examined.
3055 :    
3056 :     =item RETURN
3057 :    
3058 :     Returns TRUE if the relation needs a sort, else FALSE.
3059 :    
3060 :     =back
3061 :    
3062 :     =cut
3063 :     #: Return Type $;
3064 :     sub SortNeeded {
3065 :     # Get the parameters.
3066 :     my ($self, $relationName) = @_;
3067 :     # Declare the return variable.
3068 :     my $retVal = 0;
3069 :     # Find out if the relation is a primary entity relation.
3070 : parrello 1.43 my $entityTable = $self->{_metaData}->{Entities};
3071 : parrello 1.42 if (exists $entityTable->{$relationName}) {
3072 :     my $keyType = $entityTable->{$relationName}->{keyType};
3073 : parrello 1.43 Trace("Relation $relationName found in entity table with key type $keyType.") if T(3);
3074 : parrello 1.42 # If the key is not a hash string, we must do the sort.
3075 :     if ($keyType ne 'hash-string') {
3076 :     $retVal = 1;
3077 :     }
3078 :     }
3079 :     # Return the result.
3080 :     return $retVal;
3081 :     }
3082 :    
3083 : parrello 1.1 =head3 CreateRelationshipIndex
3084 :    
3085 :     Create an index for a relationship's relation.
3086 :    
3087 :     This is a static method.
3088 :    
3089 :     =over 4
3090 :    
3091 :     =item indexKey
3092 :    
3093 :     Type of index: either C<"From"> or C<"To">.
3094 :    
3095 :     =item relationshipName
3096 :    
3097 :     Name of the relationship.
3098 :    
3099 :     =item relationshipStructure
3100 :    
3101 :     Structure describing the relationship that the index will sort.
3102 :    
3103 :     =back
3104 :    
3105 :     =cut
3106 :    
3107 :     sub _CreateRelationshipIndex {
3108 : parrello 1.10 # Get the parameters.
3109 :     my ($indexKey, $relationshipName, $relationshipStructure) = @_;
3110 :     # Get the target relation.
3111 :     my $relationStructure = $relationshipStructure->{Relations}->{$relationshipName};
3112 :     # Create a descriptor for the link field that goes at the beginning of this index.
3113 :     my $firstField = { name => lcfirst $indexKey . '-link', order => 'ascending' };
3114 :     # Get the target index descriptor.
3115 :     my $newIndex = $relationshipStructure->{$indexKey . "Index"};
3116 :     # Add the first field to the index's field list. Due to the craziness of PERL, if the
3117 :     # index descriptor does not exist, it will be created automatically so we can add
3118 :     # the field to it.
3119 :     unshift @{$newIndex->{IndexFields}}, $firstField;
3120 : parrello 1.12 # If this is a one-to-many relationship, the "To" index is unique.
3121 :     if ($relationshipStructure->{arity} eq "1M" && $indexKey eq "To") {
3122 :     $newIndex->{Unique} = 'true';
3123 :     }
3124 : parrello 1.10 # Add the index to the relation.
3125 :     _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
3126 : parrello 1.1 }
3127 :    
3128 :     =head3 AddIndex
3129 :    
3130 :     Add an index to a relation structure.
3131 :    
3132 :     This is a static method.
3133 :    
3134 :     =over 4
3135 :    
3136 :     =item indexName
3137 :    
3138 :     Name to give to the new index.
3139 :    
3140 :     =item relationStructure
3141 :    
3142 :     Relation structure to which the new index should be added.
3143 :    
3144 :     =item newIndex
3145 :    
3146 :     New index to add.
3147 :    
3148 :     =back
3149 :    
3150 :     =cut
3151 :    
3152 :     sub _AddIndex {
3153 : parrello 1.10 # Get the parameters.
3154 :     my ($indexName, $relationStructure, $newIndex) = @_;
3155 :     # We want to re-do the index's field list. Instead of an object for each field,
3156 :     # we want a string consisting of the field name optionally followed by the token DESC.
3157 :     my @fieldList = ( );
3158 :     for my $field (@{$newIndex->{IndexFields}}) {
3159 :     # Create a string containing the field name.
3160 :     my $fieldString = $field->{name};
3161 :     # Add the ordering token if needed.
3162 :     if ($field->{order} eq "descending") {
3163 :     $fieldString .= " DESC";
3164 :     }
3165 :     # Push the result onto the field list.
3166 :     push @fieldList, $fieldString;
3167 :     }
3168 :     # Store the field list just created as the new index field list.
3169 :     $newIndex->{IndexFields} = \@fieldList;
3170 :     # Add the index to the relation's index list.
3171 :     $relationStructure->{Indexes}->{$indexName} = $newIndex;
3172 : parrello 1.1 }
3173 :    
3174 :     =head3 FixupFields
3175 :    
3176 :     This method fixes the field list for an entity or relationship. It will add the caller-specified
3177 :     relation name to fields that do not have a name and set the C<PrettySort> value as specified.
3178 :    
3179 :     This is a static method.
3180 :    
3181 :     =over 4
3182 :    
3183 :     =item structure
3184 :    
3185 :     Entity or relationship structure to be fixed up.
3186 :    
3187 :     =item defaultRelationName
3188 :    
3189 :     Default relation name to be added to the fields.
3190 :    
3191 :     =item prettySortValue
3192 :    
3193 :     C<PrettySort> value for the relation's normal fields.
3194 :    
3195 :     =item textPrettySortValue
3196 :    
3197 :     C<PrettySort> value for the relation's text fields. This value can be set to one greater than the
3198 :     normal pretty sort value so that text fields go at the end of each relation.
3199 :    
3200 :     =back
3201 :    
3202 :     =cut
3203 :    
3204 :     sub _FixupFields {
3205 : parrello 1.10 # Get the parameters.
3206 :     my ($structure, $defaultRelationName, $prettySortValue, $textPrettySortValue) = @_;
3207 :     # Insure the structure has a field list.
3208 :     if (!exists $structure->{Fields}) {
3209 :     # Here it doesn't, so we create a new one.
3210 :     $structure->{Fields} = { };
3211 :     } else {
3212 :     # Here we have a field list. Loop through its fields.
3213 :     my $fieldStructures = $structure->{Fields};
3214 :     for my $fieldName (keys %{$fieldStructures}) {
3215 : parrello 1.8 Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
3216 : parrello 1.10 my $fieldData = $fieldStructures->{$fieldName};
3217 :     # Get the field type.
3218 :     my $type = $fieldData->{type};
3219 :     # Plug in a relation name if it is needed.
3220 :     Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
3221 :     # Plug in a data generator if we need one.
3222 :     if (!exists $fieldData->{DataGen}) {
3223 :     # The data generator will use the default for the field's type.
3224 :     $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };
3225 :     }
3226 :     # Plug in the defaults for the optional data generation parameters.
3227 :     Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });
3228 :     # Add the PrettySortValue.
3229 :     $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
3230 :     }
3231 :     }
3232 : parrello 1.1 }
3233 :    
3234 :     =head3 FixName
3235 :    
3236 :     Fix the incoming field name so that it is a legal SQL column name.
3237 :    
3238 :     This is a static method.
3239 :    
3240 :     =over 4
3241 :    
3242 :     =item fieldName
3243 :    
3244 :     Field name to fix.
3245 :    
3246 :     =item RETURN
3247 :    
3248 :     Returns the fixed-up field name.
3249 :    
3250 :     =back
3251 :    
3252 :     =cut
3253 :    
3254 :     sub _FixName {
3255 : parrello 1.10 # Get the parameter.
3256 :     my ($fieldName) = @_;
3257 :     # Replace its minus signs with underscores.
3258 :     $fieldName =~ s/-/_/g;
3259 :     # Return the result.
3260 :     return $fieldName;
3261 : parrello 1.1 }
3262 :    
3263 :     =head3 FixNames
3264 :    
3265 :     Fix all the field names in a list.
3266 :    
3267 :     This is a static method.
3268 :    
3269 :     =over 4
3270 :    
3271 :     =item field1, field2, field3, ... fieldn
3272 :    
3273 :     List of field names to fix.
3274 :    
3275 :     =item RETURN
3276 :    
3277 :     Returns a list of fixed-up versions of the incoming field names.
3278 :    
3279 :     =back
3280 :    
3281 :     =cut
3282 :    
3283 :     sub _FixNames {
3284 : parrello 1.10 # Create the result list.
3285 :     my @result = ( );
3286 :     # Loop through the incoming parameters.
3287 :     for my $field (@_) {
3288 :     push @result, _FixName($field);
3289 :     }
3290 :     # Return the result.
3291 :     return @result;
3292 : parrello 1.1 }
3293 :    
3294 :     =head3 AddField
3295 :    
3296 :     Add a field to a field list.
3297 :    
3298 :     This is a static method.
3299 :    
3300 :     =over 4
3301 :    
3302 :     =item structure
3303 :    
3304 :     Structure (usually an entity or relationship) that is to contain the field.
3305 :    
3306 :     =item fieldName
3307 :    
3308 :     Name of the new field.
3309 :    
3310 :     =item fieldData
3311 :    
3312 :     Structure containing the data to put in the field.
3313 :    
3314 :     =back
3315 :    
3316 :     =cut
3317 :    
3318 :     sub _AddField {
3319 : parrello 1.10 # Get the parameters.
3320 :     my ($structure, $fieldName, $fieldData) = @_;
3321 :     # Create the field structure by copying the incoming data.
3322 :     my $fieldStructure = {%{$fieldData}};
3323 :     # Get a reference to the field list itself.
3324 :     my $fieldList = $structure->{Fields};
3325 :     # Add the field to the field list.
3326 :     $fieldList->{$fieldName} = $fieldStructure;
3327 : parrello 1.1 }
3328 :    
3329 :     =head3 ReOrderRelationTable
3330 :    
3331 :     This method will take a relation table and re-sort it according to the implicit ordering of the
3332 :     C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.
3333 :     This requires creating a new hash that contains the field name in the C<name> property but doesn't
3334 :     have the C<PrettySort> property, and then inserting that new hash into the field list.
3335 :    
3336 :     This is a static method.
3337 :    
3338 :     =over 4
3339 :    
3340 :     =item relationTable
3341 :    
3342 :     Relation hash to be reformatted into a list.
3343 :    
3344 :     =item RETURN
3345 :    
3346 :     A list of field hashes.
3347 :    
3348 :     =back
3349 :    
3350 :     =cut
3351 :    
3352 :     sub _ReOrderRelationTable {
3353 : parrello 1.10 # Get the parameters.
3354 :     my ($relationTable) = @_;
3355 :     # Create the return list.
3356 :     my @resultList;
3357 :     # Rather than copy all the fields in a single pass, we make multiple passes and only copy
3358 :     # fields whose PrettySort value matches the current pass number. This process continues
3359 :     # until we process all the fields in the relation.
3360 :     my $fieldsLeft = (values %{$relationTable});
3361 :     for (my $sortPass = 1; $fieldsLeft > 0; $sortPass++) {
3362 :     # Loop through the fields. Note that we lexically sort the fields. This makes field name
3363 :     # secondary to pretty-sort number in the final ordering.
3364 :     for my $fieldName (sort keys %{$relationTable}) {
3365 :     # Get this field's data.
3366 :     my $fieldData = $relationTable->{$fieldName};
3367 :     # Verify the sort pass.
3368 :     if ($fieldData->{PrettySort} == $sortPass) {
3369 :     # Here we're in the correct pass. Denote we've found a field.
3370 :     $fieldsLeft--;
3371 :     # The next step is to create the field structure. This done by copying all
3372 :     # of the field elements except PrettySort and adding the name.
3373 :     my %thisField;
3374 :     for my $property (keys %{$fieldData}) {
3375 :     if ($property ne 'PrettySort') {
3376 :     $thisField{$property} = $fieldData->{$property};
3377 :     }
3378 :     }
3379 :     $thisField{name} = $fieldName;
3380 :     # Now we add this field to the end of the result list.
3381 :     push @resultList, \%thisField;
3382 :     }
3383 :     }
3384 :     }
3385 :     # Return a reference to the result list.
3386 :     return \@resultList;
3387 : parrello 1.1
3388 :     }
3389 :    
3390 :     =head3 IsPrimary
3391 :    
3392 :     Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary
3393 :     if it has the same name as an entity or relationship.
3394 :    
3395 :     This is an instance method.
3396 :    
3397 :     =over 4
3398 :    
3399 :     =item relationName
3400 :    
3401 :     Name of the relevant relation.
3402 :    
3403 :     =item RETURN
3404 :    
3405 :     Returns TRUE for a primary relation, else FALSE.
3406 :    
3407 :     =back
3408 :    
3409 :     =cut
3410 :    
3411 :     sub _IsPrimary {
3412 : parrello 1.10 # Get the parameters.
3413 :     my ($self, $relationName) = @_;
3414 :     # Check for the relation in the entity table.
3415 :     my $entityTable = $self->{_metaData}->{Entities};
3416 :     my $retVal = exists $entityTable->{$relationName};
3417 :     if (! $retVal) {
3418 :     # Check for it in the relationship table.
3419 :     my $relationshipTable = $self->{_metaData}->{Relationships};
3420 :     $retVal = exists $relationshipTable->{$relationName};
3421 :     }
3422 :     # Return the determination indicator.
3423 :     return $retVal;
3424 : parrello 1.1 }
3425 :    
3426 :     =head3 FindRelation
3427 :    
3428 :     Return the descriptor for the specified relation.
3429 :    
3430 :     This is an instance method.
3431 :    
3432 :     =over 4
3433 :    
3434 :     =item relationName
3435 :    
3436 :     Name of the relation whose descriptor is to be returned.
3437 :    
3438 :     =item RETURN
3439 :    
3440 :     Returns the object that describes the relation's indexes and fields.
3441 :    
3442 :     =back
3443 :    
3444 :     =cut
3445 :     sub _FindRelation {
3446 : parrello 1.10 # Get the parameters.
3447 :     my ($self, $relationName) = @_;
3448 :     # Get the relation's structure from the master relation table in the metadata structure.
3449 :     my $metaData = $self->{_metaData};
3450 :     my $retVal = $metaData->{RelationTable}->{$relationName};
3451 :     # Return it to the caller.
3452 :     return $retVal;
3453 : parrello 1.1 }
3454 :    
3455 :     =head2 HTML Documentation Utility Methods
3456 :    
3457 :     =head3 ComputeRelationshipSentence
3458 :    
3459 :     The relationship sentence consists of the relationship name between the names of the
3460 :     two related entities and an arity indicator.
3461 :    
3462 :     This is a static method.
3463 :    
3464 :     =over 4
3465 :    
3466 :     =item relationshipName
3467 :    
3468 :     Name of the relationship.
3469 :    
3470 :     =item relationshipStructure
3471 :    
3472 :     Relationship structure containing the relationship's description and properties.
3473 :    
3474 :     =item RETURN
3475 :    
3476 :     Returns a string containing the entity names on either side of the relationship name and an
3477 :     indicator of the arity.
3478 :    
3479 :     =back
3480 :    
3481 :     =cut
3482 :    
3483 :     sub _ComputeRelationshipSentence {
3484 : parrello 1.10 # Get the parameters.
3485 :     my ($relationshipName, $relationshipStructure) = @_;
3486 :     # Format the relationship sentence.
3487 :     my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";
3488 :     # Compute the arity.
3489 :     my $arityCode = $relationshipStructure->{arity};
3490 :     my $arity = $ArityTable{$arityCode};
3491 :     $result .= " ($arity)";
3492 :     return $result;
3493 : parrello 1.1 }
3494 :    
3495 :     =head3 ComputeRelationshipHeading
3496 :    
3497 :     The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
3498 :     names hyperlinked to the appropriate entity sections of the document.
3499 :    
3500 :     This is a static method.
3501 :    
3502 :     =over 4
3503 :    
3504 :     =item relationshipName
3505 :    
3506 :     Name of the relationship.
3507 :    
3508 :     =item relationshipStructure
3509 :    
3510 :     Relationship structure containing the relationship's description and properties.
3511 :    
3512 :     =item RETURN
3513 :    
3514 :     Returns a string containing the entity names on either side of the relationship name with the entity
3515 :     names hyperlinked.
3516 :    
3517 :     =back
3518 :    
3519 :     =cut
3520 :    
3521 :     sub _ComputeRelationshipHeading {
3522 : parrello 1.10 # Get the parameters.
3523 :     my ($relationshipName, $relationshipStructure) = @_;
3524 :     # Get the FROM and TO entity names.
3525 :     my $fromEntity = $relationshipStructure->{from};
3526 :     my $toEntity = $relationshipStructure->{to};
3527 :     # Format a relationship sentence with hyperlinks in it.
3528 :     my $result = "<a href=\"#$fromEntity\">$fromEntity</a> $relationshipName <a href=\"#$toEntity\">$toEntity</a>";
3529 :     return $result;
3530 : parrello 1.1 }
3531 :    
3532 :     =head3 ShowRelationTable
3533 :    
3534 :     Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
3535 :     table with three columns-- the field name, the field type, and the field description.
3536 :    
3537 :     This is a static method.
3538 :    
3539 :     =over 4
3540 :    
3541 :     =item relationName
3542 :    
3543 :     Name of the relation being formatted.
3544 :    
3545 :     =item relationData
3546 :    
3547 :     Hash containing the relation's fields and indexes.
3548 :    
3549 :     =item RETURN
3550 :    
3551 :     Returns an HTML string that can be used to display the relation name and all of its fields.
3552 :    
3553 :     =back
3554 :    
3555 :     =cut
3556 :    
3557 :     sub _ShowRelationTable {
3558 : parrello 1.10 # Get the parameters.
3559 :     my ($relationName, $relationData) = @_;
3560 :     # Start the relation's field table.
3561 :     my $htmlString = _OpenFieldTable($relationName);
3562 :     # Loop through the fields.
3563 :     for my $field (@{$relationData->{Fields}}) {
3564 :     $htmlString .= _ShowField($field);
3565 :     }
3566 :     # Close this relation's field table.
3567 :     $htmlString .= &_CloseTable;
3568 :     # Now we show the relation's indexes.
3569 :     $htmlString .= "<ul>\n";
3570 :     my $indexTable = $relationData->{Indexes};
3571 :     for my $indexName (sort keys %{$indexTable}) {
3572 :     my $indexData = $indexTable->{$indexName};
3573 :     # Determine whether or not the index is unique.
3574 :     my $fullName = $indexName;
3575 :     if (exists $indexData->{Unique} && $indexData->{Unique} eq "true") {
3576 :     $fullName .= " (unique)";
3577 :     }
3578 :     # Start an HTML list item for this index.
3579 :     $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
3580 :     # Add any note text.
3581 :     if (my $note = $indexData->{Notes}) {
3582 :     $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";
3583 :     }
3584 :     # Add the fiield list.
3585 :     $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
3586 :     # Close this entry.
3587 :     $htmlString .= "</ul></li>\n";
3588 :     }
3589 :     # Close off the index list.
3590 :     $htmlString .= "</ul>\n";
3591 : parrello 1.1 }
3592 :    
3593 :     =head3 OpenFieldTable
3594 :    
3595 :     This method creates the header string for the field table generated by L</ShowMetaData>.
3596 :    
3597 :     This is a static method.
3598 :    
3599 :     =over 4
3600 :    
3601 :     =item tablename
3602 :    
3603 :     Name of the table whose fields will be displayed.
3604 :    
3605 :     =item RETURN
3606 :    
3607 :     Returns a string containing the HTML for a field table's header.
3608 :    
3609 :     =back
3610 :    
3611 :     =cut
3612 :    
3613 :     sub _OpenFieldTable {
3614 : parrello 1.10 my ($tablename) = @_;
3615 :     return _OpenTable($tablename, 'Field', 'Type', 'Description');
3616 : parrello 1.1 }
3617 :    
3618 :     =head3 OpenTable
3619 :    
3620 :     This method creates the header string for an HTML table.
3621 :    
3622 :     This is a static method.
3623 :    
3624 :     =over 4
3625 :    
3626 :     =item tablename
3627 :    
3628 :     Title of the table.
3629 :    
3630 :     =item colName1, colName2, ..., colNameN
3631 :    
3632 :     List of column names.
3633 :    
3634 :     =item RETURN
3635 :    
3636 :     Returns a string containing the HTML for the desired table's header.
3637 :    
3638 :     =back
3639 :    
3640 :     =cut
3641 :    
3642 :     sub _OpenTable {
3643 : parrello 1.10 # Get the parameters.
3644 :     my ($tablename, @colNames) = @_;
3645 :     # Compute the number of columns.
3646 :     my $colCount = @colNames;
3647 :     # Generate the title row.
3648 :     my $htmlString = "<p><table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";
3649 :     # Loop through the columns, adding the column header rows.
3650 :     $htmlString .= "<tr>";
3651 :     for my $colName (@colNames) {
3652 :     $htmlString .= "<th>$colName</th>";
3653 :     }
3654 :     $htmlString .= "</tr>\n";
3655 :     return $htmlString;
3656 : parrello 1.1 }
3657 :    
3658 :     =head3 CloseTable
3659 :    
3660 :     This method returns the HTML for closing a table.
3661 :    
3662 :     This is a static method.
3663 :    
3664 :     =cut
3665 :    
3666 :     sub _CloseTable {
3667 : parrello 1.10 return "</table></p>\n";
3668 : parrello 1.1 }
3669 :    
3670 :     =head3 ShowField
3671 :    
3672 :     This method returns the HTML for displaying a row of field information in a field table.
3673 :    
3674 :     This is a static method.
3675 :    
3676 :     =over 4
3677 :    
3678 :     =item fieldData
3679 :    
3680 :     Table of data about the field.
3681 :    
3682 :     =item RETURN
3683 :    
3684 :     Returns an HTML string for a table row that shows the field's name, type, and description.
3685 :    
3686 :     =back
3687 :    
3688 :     =cut
3689 :    
3690 :     sub _ShowField {
3691 : parrello 1.10 # Get the parameters.
3692 :     my ($fieldData) = @_;
3693 :     # Create the HTML string.
3694 :     my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";
3695 :     # If we have content, add it as a third column.
3696 :     if (exists $fieldData->{Notes}) {
3697 :     $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";
3698 :     }
3699 :     # Close off the row.
3700 :     $htmlString .= "</tr>\n";
3701 :     # Return the result.
3702 :     return $htmlString;
3703 : parrello 1.1 }
3704 :    
3705 :     =head3 HTMLNote
3706 :    
3707 :     Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3708 :     supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3709 :     Except for C<[p]>, all the codes are closed by slash-codes. So, for
3710 :     example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3711 :    
3712 :     This is a static method.
3713 :    
3714 :     =over 4
3715 :    
3716 :     =item dataString
3717 :    
3718 :     String to convert to HTML.
3719 :    
3720 :     =item RETURN
3721 :    
3722 :     An HTML string derived from the input string.
3723 :    
3724 :     =back
3725 :    
3726 :     =cut
3727 :    
3728 :     sub _HTMLNote {
3729 : parrello 1.10 # Get the parameter.
3730 :     my ($dataString) = @_;
3731 :     # Substitute the codes.
3732 :     $dataString =~ s!\[(/?[bi])\]!<$1>!g;
3733 :     $dataString =~ s!\[p\]!</p><p>!g;
3734 :     # Return the result.
3735 :     return $dataString;
3736 : parrello 1.1 }
3737 :    
3738 :     =head2 Data Generation Utilities
3739 :    
3740 :     =head3 IntGen
3741 :    
3742 :     C<< my $integer = IntGen($min, $max); >>
3743 :    
3744 :     Returns a random number between the specified minimum and maximum (inclusive).
3745 :    
3746 :     =over 4
3747 :    
3748 :     =item min
3749 :    
3750 :     Minimum permissible return value.
3751 :    
3752 :     =item max
3753 :    
3754 :     Maximum permissible return value.
3755 :    
3756 :     =item RETURN
3757 :    
3758 :     Returns a value no lower than the minimum and no greater than the maximum.
3759 :    
3760 :     =back
3761 :    
3762 :     =cut
3763 :    
3764 :     sub IntGen {
3765 : parrello 1.10 # Get the parameters.
3766 :     my ($min, $max) = @_;
3767 :     # Determine the range of possible values. Note we put some space well above the
3768 :     # maximum value to give it a fighting chance of apppearing in the list.
3769 :     my $span = $max + 0.99 - $min;
3770 :     # Create an integer in the range.
3771 :     my $retVal = $min + int(rand($span));
3772 :     # Return the result.
3773 :     return $retVal;
3774 : parrello 1.1 }
3775 :    
3776 :     =head3 RandChar
3777 :    
3778 :     C<< my $char = RandChar($sourceString); >>
3779 :    
3780 :     Select a random character from a string.
3781 :    
3782 :     =over 4
3783 :    
3784 :     =item sourceString
3785 :    
3786 :     String from which the random character should be selected.
3787 :    
3788 :     =item RETURN
3789 :    
3790 :     Returns a single character from the incoming string.
3791 :    
3792 :     =back
3793 :    
3794 :     =cut
3795 :    
3796 :     sub RandChar {
3797 : parrello 1.10 # Get the parameter.
3798 :     my ($sourceString) = @_;
3799 :     # Select a random character.
3800 :     my $retVal = IntGen(0, (length $sourceString) - 1);
3801 :     # Return it.
3802 :     return substr($sourceString, $retVal, 1);
3803 : parrello 1.1 }
3804 :    
3805 :     =head3 RandChars
3806 :    
3807 :     C<< my $string = RandChars($sourceString, $length); >>
3808 :    
3809 :     Create a string from characters taken from a source string.
3810 :    
3811 :     =over 4
3812 :    
3813 :     =item sourceString
3814 :    
3815 :     String from which the random characters should be selected.
3816 :    
3817 :     =item length
3818 :    
3819 :     Number of characters to put in the output string.
3820 :    
3821 :     =item RETURN
3822 :    
3823 :     Returns a string of the specified length consisting of characters taken from the
3824 :     source string.
3825 :    
3826 :     =back
3827 :    
3828 :     =cut
3829 :    
3830 :     sub RandChars {
3831 : parrello 1.10 # Get the parameters.
3832 :     my ($sourceString, $length) = @_;
3833 :     # Call RandChar repeatedly to generate the string.
3834 :     my $retVal = "";
3835 :     for (my $i = 0; $i < $length; $i++) {
3836 :     $retVal .= RandChar($sourceString);
3837 :     }
3838 :     # Return the result.
3839 :     return $retVal;
3840 : parrello 1.1 }
3841 :    
3842 :     =head3 RandParam
3843 :    
3844 :     C<< my $value = RandParam($parm1, $parm2, ... $parmN); >>
3845 :    
3846 :     Return a randomly-selected value from the parameter list.
3847 :    
3848 :     =over 4
3849 :    
3850 :     =item parm1, parm2, ... parmN
3851 :    
3852 :     List of values of which one will be selected.
3853 :    
3854 :     =item RETURN
3855 :    
3856 :     Returns a randomly-chosen value from the specified list.
3857 :    
3858 :     =back
3859 :    
3860 :     =cut
3861 :    
3862 :     sub RandParam {
3863 : parrello 1.10 # Get the parameter.
3864 :     my @parms = @_;
3865 :     # Choose a random parameter from the list.
3866 :     my $chosenIndex = IntGen(0, $#parms);
3867 :     return $parms[$chosenIndex];
3868 : parrello 1.1 }
3869 :    
3870 :     =head3 StringGen
3871 :    
3872 :     C<< my $string = StringGen($pattern1, $pattern2, ... $patternN); >>
3873 :    
3874 :     Returns a random string derived from a randomly-chosen format pattern. The pattern
3875 :     can either be a number (indicating the number of characters desired, or the letter
3876 :     C<P> followed by a picture. The picture should contain C<A> when a letter is desired,
3877 :     C<9> when a digit is desired, C<V> when a vowel is desired, C<K> when a consonant is
3878 :     desired, and C<X> when a letter or a digit is desired. Any other character will be
3879 :     translated as a literal.
3880 :    
3881 :     =over 4
3882 :    
3883 :     =item pattern1, pattern2, ... patternN
3884 :    
3885 :     List of patterns to be used to generate string values.
3886 :    
3887 :     =item RETURN
3888 :    
3889 :     A single string generated from a pattern.
3890 :    
3891 :     =back
3892 :    
3893 :     =cut
3894 :    
3895 :     sub StringGen {
3896 : parrello 1.10 # Get the parameters.
3897 :     my @patterns = @_;
3898 :     # Choose the appropriate pattern.
3899 :     my $chosenPattern = RandParam(@patterns);
3900 :     # Declare the return variable.
3901 :     my $retVal = "";
3902 :     # Determine whether this is a count or a picture pattern.
3903 :     if ($chosenPattern =~ m/^\d+/) {
3904 :     # Here we have a count. Get the string of source characters.
3905 :     my $letterString = $PictureTable{'X'};
3906 :     my $stringLen = length $letterString;
3907 :     # Save the number of characters we have to generate.
3908 :     my $charsLeft = $chosenPattern;
3909 :     # Loop until the return variable is full.
3910 :     while ($charsLeft > 0) {
3911 :     # Generate a random position in the soruce string.
3912 :     my $stringIndex = IntGen(0, $stringLen - 1);
3913 :     # Compute the number of characters to pull out of the source string.
3914 :     my $chunkSize = $stringLen - $stringIndex;
3915 :     if ($chunkSize > $charsLeft) { $chunkSize = $charsLeft; }
3916 :     # Stuff this chunk into the return value.
3917 :     $retVal .= substr($letterString, $stringIndex, $chunkSize);
3918 :     # Record the data moved.
3919 :     $charsLeft -= $chunkSize;
3920 :     }
3921 :     } elsif ($chosenPattern =~ m/^P/) {
3922 :     # Here we have a picture string. We will move through the picture one
3923 :     # character at a time generating data.
3924 :     for (my $i = 1; $i < length $chosenPattern; $i++) {
3925 :     # Get this picture character.
3926 :     my $chr = substr($chosenPattern, $i, 1);
3927 :     # Check to see if the picture char is one we recognize.
3928 :     if (exists $PictureTable{$chr}) {
3929 :     # Choose a random character from the available values for this
3930 :     # picture character.
3931 :     $retVal .= RandChar($PictureTable{$chr});
3932 :     } else {
3933 :     # Copy in the picture character as a literal.
3934 :     $retVal .= $chr;
3935 :     }
3936 :     }
3937 :     } else {
3938 :     # Here we have neither a picture string or a letter count, so we treat
3939 :     # the string as a literal.
3940 :     $retVal = $chosenPattern;
3941 :     }
3942 :     # Return the string formed.
3943 :     return $retVal;
3944 : parrello 1.1 }
3945 :    
3946 :     =head3 DateGen
3947 :    
3948 :     C<< my $date = DateGen($startDayOffset, $endDayOffset, $minutes); >>
3949 :    
3950 :     Return a numeric timestamp within the specified range of days with the specified minute
3951 :     value. The range of days is specified relevant to the current day. Thus, the call
3952 :    
3953 :     C<< my $date = DateGen(-1, 5, 720); >>
3954 :    
3955 :     will return a timestamp at noon (72 minutes past midnight) sometime during the week that
3956 :     began on the preceding day. If you want a random minute of the day, simply combine with
3957 :     a call to L</IntGen>, as follows.
3958 :    
3959 :     C<< my $date = DateGen(-1, 5, IntGen(0, 1439)); >>
3960 :    
3961 :     =over 4
3962 :    
3963 :     =item startDayOffset
3964 :    
3965 :     The earliest day that can be returned, relative to the current day.
3966 :    
3967 :     =item endDayOffset
3968 :    
3969 :     The latest day that can be returned, related to the current day.
3970 :    
3971 :     =item minutes
3972 :    
3973 :     Number of minutes into the selected day that should be used.
3974 :    
3975 :     =back
3976 :    
3977 :     =cut
3978 :    
3979 :     sub DateGen {
3980 : parrello 1.10 # Get the parameters.
3981 :     my ($startDayOffset, $endDayOffset, $minutes) = @_;
3982 :     # Get midnight of the current day.
3983 :     my $now = time();
3984 :     my ($sec, $min, $hour) = localtime($now);
3985 :     my $today = $now - (($hour * 60 + $min) * 60 + $sec);
3986 :     # Compute the day we want.
3987 :     my $newDay = IntGen($startDayOffset, $endDayOffset) * 86400 + $today;
3988 :     # Add the minutes.
3989 :     my $retVal = $newDay + $minutes * 60;
3990 :     # Return the result.
3991 :     return $retVal;
3992 : parrello 1.1 }
3993 :    
3994 :     =head3 FloatGen
3995 :    
3996 :     C<< my $number = FloatGen($min, $max); >>
3997 :    
3998 :     Return a random floating-point number greater than or equal to the specified minimum and
3999 :     less than the specified maximum.
4000 :    
4001 :     =over 4
4002 :    
4003 :     =item min
4004 :    
4005 :     Minimum permissible value for the number returned.
4006 :    
4007 :     =item max
4008 :    
4009 :     Maximum permissible value for the number returned.
4010 :    
4011 :     =item RETURN
4012 :    
4013 :     Returns a floating-point number anywhere in the specified range.
4014 :    
4015 :     =back
4016 :    
4017 :     =cut
4018 :    
4019 :     sub FloatGen {
4020 : parrello 1.10 # Get the parameters.
4021 :     my ($min, $max) = @_;
4022 :     # Generate the result.
4023 :     my $retVal = rand($max - $min) + $min;
4024 :     return $retVal;
4025 : parrello 1.1 }
4026 :    
4027 :     =head3 ListGen
4028 :    
4029 :     C<< my @list = ListGen($pattern, $count); >>
4030 :    
4031 :     Return a list containing a fixed number of randomly-generated strings.
4032 :    
4033 :     =over 4
4034 :    
4035 :     =item pattern
4036 :    
4037 :     A pattern (in the form expected by L</StringGen>) that should be used to generate the
4038 :     strings in the list.
4039 :    
4040 :     =item count
4041 :    
4042 :     The number of list entries to generate.
4043 :    
4044 :     =item RETURN
4045 :    
4046 :     Returns a list consisting of the specified number of strings.
4047 :    
4048 :     =back
4049 :    
4050 :     =cut
4051 :    
4052 :     sub ListGen {
4053 : parrello 1.10 # Get the parameters.
4054 :     my ($pattern, $count) = @_;
4055 :     # Generate the list.
4056 :     my @retVal = ();
4057 :     for (my $i = 0; $i < $count; $i++) {
4058 :     push @retVal, StringGen($pattern);
4059 :     }
4060 :     # Return it.
4061 :     return @retVal;
4062 : parrello 1.1 }
4063 :    
4064 : overbeek 1.11 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3