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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.46 - (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 :     my $count = $erdb->GetCount(['Feature', 'Genome'], 'Genome(genus-species) LIKE ?',
1395 :     ['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 :     # Create the SQL command suffix to get the desired records.
1437 :     my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1438 :     $filter);
1439 :     # Prefix it with text telling it we want a record count.
1440 :     my $firstObject = $mappedNameListRef->[0];
1441 :     my $command = "SELECT COUNT($firstObject.id) $suffix";
1442 :     # Prepare and execute the command.
1443 :     my $sth = $self->_GetStatementHandle($command, $params);
1444 :     # Get the count value.
1445 :     ($retVal) = $sth->fetchrow_array();
1446 :     # Check for a problem.
1447 :     if (! defined($retVal)) {
1448 :     if ($sth->err) {
1449 :     # Here we had an SQL error.
1450 :     Confess("Error retrieving row count: " . $sth->errstr());
1451 :     } else {
1452 :     # Here we have no result.
1453 :     Confess("No result attempting to retrieve row count.");
1454 :     }
1455 :     }
1456 :     # Return the result.
1457 :     return $retVal;
1458 :     }
1459 :    
1460 : parrello 1.1 =head3 ComputeObjectSentence
1461 :    
1462 : parrello 1.18 C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>
1463 : parrello 1.1
1464 :     Check an object name, and if it is a relationship convert it to a relationship sentence.
1465 :    
1466 :     =over 4
1467 :    
1468 :     =item objectName
1469 :    
1470 :     Name of the entity or relationship.
1471 :    
1472 :     =item RETURN
1473 :    
1474 :     Returns a string containing the entity name or a relationship sentence.
1475 :    
1476 :     =back
1477 :    
1478 :     =cut
1479 :    
1480 :     sub ComputeObjectSentence {
1481 : parrello 1.10 # Get the parameters.
1482 :     my ($self, $objectName) = @_;
1483 :     # Set the default return value.
1484 :     my $retVal = $objectName;
1485 :     # Look for the object as a relationship.
1486 :     my $relTable = $self->{_metaData}->{Relationships};
1487 :     if (exists $relTable->{$objectName}) {
1488 :     # Get the relationship sentence.
1489 :     $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});
1490 :     }
1491 :     # Return the result.
1492 :     return $retVal;
1493 : parrello 1.1 }
1494 :    
1495 :     =head3 DumpRelations
1496 :    
1497 : parrello 1.18 C<< $erdb->DumpRelations($outputDirectory); >>
1498 : parrello 1.1
1499 :     Write the contents of all the relations to tab-delimited files in the specified directory.
1500 :     Each file will have the same name as the relation dumped, with an extension of DTX.
1501 :    
1502 :     =over 4
1503 :    
1504 :     =item outputDirectory
1505 :    
1506 :     Name of the directory into which the relation files should be dumped.
1507 :    
1508 :     =back
1509 :    
1510 :     =cut
1511 :    
1512 :     sub DumpRelations {
1513 : parrello 1.10 # Get the parameters.
1514 :     my ($self, $outputDirectory) = @_;
1515 :     # Now we need to run through all the relations. First, we loop through the entities.
1516 :     my $metaData = $self->{_metaData};
1517 :     my $entities = $metaData->{Entities};
1518 :     for my $entityName (keys %{$entities}) {
1519 :     my $entityStructure = $entities->{$entityName};
1520 :     # Get the entity's relations.
1521 :     my $relationList = $entityStructure->{Relations};
1522 :     # Loop through the relations, dumping them.
1523 :     for my $relationName (keys %{$relationList}) {
1524 :     my $relation = $relationList->{$relationName};
1525 :     $self->_DumpRelation($outputDirectory, $relationName, $relation);
1526 :     }
1527 :     }
1528 :     # Next, we loop through the relationships.
1529 :     my $relationships = $metaData->{Relationships};
1530 :     for my $relationshipName (keys %{$relationships}) {
1531 :     my $relationshipStructure = $relationships->{$relationshipName};
1532 :     # Dump this relationship's relation.
1533 :     $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
1534 :     }
1535 : parrello 1.1 }
1536 :    
1537 :     =head3 InsertObject
1538 :    
1539 : parrello 1.18 C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>
1540 : parrello 1.1
1541 :     Insert an object into the database. The object is defined by a type name and then a hash
1542 :     of field names to values. Field values in the primary relation are represented by scalars.
1543 :     (Note that for relationships, the primary relation is the B<only> relation.)
1544 :     Field values for the other relations comprising the entity are always list references. For
1545 :     example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
1546 :     C<ZP_00210270.1> and C<gi|46206278>.
1547 :    
1548 : parrello 1.18 C<< $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>
1549 : parrello 1.1
1550 :     The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
1551 :     property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
1552 :    
1553 : 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'}); >>
1554 : parrello 1.1
1555 :     =over 4
1556 :    
1557 :     =item newObjectType
1558 :    
1559 :     Type name of the object to insert.
1560 :    
1561 :     =item fieldHash
1562 :    
1563 :     Hash of field names to values.
1564 :    
1565 :     =item RETURN
1566 :    
1567 :     Returns 1 if successful, 0 if an error occurred.
1568 :    
1569 :     =back
1570 :    
1571 :     =cut
1572 :    
1573 :     sub InsertObject {
1574 : parrello 1.10 # Get the parameters.
1575 :     my ($self, $newObjectType, $fieldHash) = @_;
1576 :     # Denote that so far we appear successful.
1577 :     my $retVal = 1;
1578 :     # Get the database handle.
1579 :     my $dbh = $self->{_dbh};
1580 :     # Get the relation list.
1581 :     my $relationTable = $self->_GetRelationTable($newObjectType);
1582 :     # Loop through the relations. We'll build insert statements for each one. If a relation is
1583 :     # secondary, we may end up generating multiple insert statements. If an error occurs, we
1584 :     # stop the loop.
1585 :     my @relationList = keys %{$relationTable};
1586 :     for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
1587 :     my $relationName = $relationList[$i];
1588 :     my $relationDefinition = $relationTable->{$relationName};
1589 :     # Get the relation's fields. For each field we will collect a value in the corresponding
1590 :     # position of the @valueList array. If one of the fields is missing, we will add it to the
1591 :     # @missing list.
1592 :     my @fieldList = @{$relationDefinition->{Fields}};
1593 :     my @fieldNameList = ();
1594 :     my @valueList = ();
1595 :     my @missing = ();
1596 :     my $recordCount = 1;
1597 :     for my $fieldDescriptor (@fieldList) {
1598 :     # Get the field name and save it. Note we need to fix it up so the hyphens
1599 :     # are converted to underscores.
1600 :     my $fieldName = $fieldDescriptor->{name};
1601 :     push @fieldNameList, _FixName($fieldName);
1602 :     # Look for the named field in the incoming structure. Note that we are looking
1603 :     # for the real field name, not the fixed-up one!
1604 :     if (exists $fieldHash->{$fieldName}) {
1605 :     # Here we found the field. Stash it in the value list.
1606 :     my $value = $fieldHash->{$fieldName};
1607 :     push @valueList, $value;
1608 :     # If the value is a list, we may need to increment the record count.
1609 :     if (ref $value eq "ARRAY") {
1610 :     my $thisCount = @{$value};
1611 :     if ($recordCount == 1) {
1612 :     # Here we have our first list, so we save its count.
1613 :     $recordCount = $thisCount;
1614 :     } elsif ($recordCount != $thisCount) {
1615 :     # Here we have a second list, so its length has to match the
1616 :     # previous lists.
1617 :     Trace("Field $value in new $newObjectType object has an invalid list length $thisCount. Expected $recordCount.") if T(0);
1618 :     $retVal = 0;
1619 :     }
1620 :     }
1621 :     } else {
1622 :     # Here the field is not present. Flag it as missing.
1623 :     push @missing, $fieldName;
1624 :     }
1625 :     }
1626 :     # If we are the primary relation, add the new-record flag.
1627 :     if ($relationName eq $newObjectType) {
1628 :     push @valueList, 1;
1629 :     push @fieldNameList, "new_record";
1630 :     }
1631 :     # Only proceed if there are no missing fields.
1632 :     if (@missing > 0) {
1633 :     Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
1634 :     join(' ', @missing)) if T(1);
1635 :     } else {
1636 :     # Build the INSERT statement.
1637 :     my $statement = "INSERT INTO $relationName (" . join (', ', @fieldNameList) .
1638 :     ") VALUES (";
1639 :     # Create a marker list of the proper size and put it in the statement.
1640 :     my @markers = ();
1641 :     while (@markers < @fieldNameList) { push @markers, '?'; }
1642 :     $statement .= join(', ', @markers) . ")";
1643 :     # We have the insert statement, so prepare it.
1644 :     my $sth = $dbh->prepare_command($statement);
1645 :     Trace("Insert statement prepared: $statement") if T(3);
1646 :     # Now we loop through the values. If a value is scalar, we use it unmodified. If it's
1647 :     # a list, we use the current element. The values are stored in the @parameterList array.
1648 :     my $done = 0;
1649 :     for (my $i = 0; $i < $recordCount; $i++) {
1650 :     # Clear the parameter list array.
1651 :     my @parameterList = ();
1652 :     # Loop through the values.
1653 :     for my $value (@valueList) {
1654 :     # Check to see if this is a scalar value.
1655 :     if (ref $value eq "ARRAY") {
1656 :     # Here we have a list value. Pull the current entry.
1657 :     push @parameterList, $value->[$i];
1658 :     } else {
1659 :     # Here we have a scalar value. Use it unmodified.
1660 :     push @parameterList, $value;
1661 :     }
1662 :     }
1663 :     # Execute the INSERT statement with the specified parameter list.
1664 :     $retVal = $sth->execute(@parameterList);
1665 :     if (!$retVal) {
1666 :     my $errorString = $sth->errstr();
1667 :     Trace("Insert error: $errorString.") if T(0);
1668 :     }
1669 :     }
1670 :     }
1671 :     }
1672 :     # Return the success indicator.
1673 :     return $retVal;
1674 : parrello 1.1 }
1675 :    
1676 :     =head3 LoadTable
1677 :    
1678 : parrello 1.18 C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>
1679 : parrello 1.1
1680 : parrello 1.9 Load data from a tab-delimited file into a specified table, optionally re-creating the table
1681 :     first.
1682 : parrello 1.1
1683 :     =over 4
1684 :    
1685 :     =item fileName
1686 :    
1687 :     Name of the file from which the table data should be loaded.
1688 :    
1689 :     =item relationName
1690 :    
1691 :     Name of the relation to be loaded. This is the same as the table name.
1692 :    
1693 :     =item truncateFlag
1694 :    
1695 :     TRUE if the table should be dropped and re-created, else FALSE
1696 :    
1697 :     =item RETURN
1698 :    
1699 : parrello 1.28 Returns a statistical object containing a list of the error messages.
1700 : parrello 1.1
1701 :     =back
1702 :    
1703 :     =cut
1704 :     sub LoadTable {
1705 : parrello 1.10 # Get the parameters.
1706 :     my ($self, $fileName, $relationName, $truncateFlag) = @_;
1707 :     # Create the statistical return object.
1708 :     my $retVal = _GetLoadStats();
1709 :     # Trace the fact of the load.
1710 :     Trace("Loading table $relationName from $fileName") if T(2);
1711 :     # Get the database handle.
1712 :     my $dbh = $self->{_dbh};
1713 : parrello 1.22 # Get the input file size.
1714 :     my $fileSize = -s $fileName;
1715 : parrello 1.10 # Get the relation data.
1716 :     my $relation = $self->_FindRelation($relationName);
1717 :     # Check the truncation flag.
1718 :     if ($truncateFlag) {
1719 :     Trace("Creating table $relationName") if T(2);
1720 : parrello 1.19 # Compute the row count estimate. We take the size of the load file,
1721 :     # divide it by the estimated row size, and then multiply by 1.5 to
1722 :     # leave extra room. We postulate a minimum row count of 1000 to
1723 :     # prevent problems with incoming empty load files.
1724 :     my $rowSize = $self->EstimateRowSize($relationName);
1725 :     my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1726 : parrello 1.10 # Re-create the table without its index.
1727 : parrello 1.19 $self->CreateTable($relationName, 0, $estimate);
1728 : parrello 1.10 # If this is a pre-index DBMS, create the index here.
1729 :     if ($dbh->{_preIndex}) {
1730 :     eval {
1731 :     $self->CreateIndex($relationName);
1732 :     };
1733 :     if ($@) {
1734 :     $retVal->AddMessage($@);
1735 :     }
1736 :     }
1737 :     }
1738 : parrello 1.3 # Load the table.
1739 : parrello 1.10 my $rv;
1740 :     eval {
1741 : parrello 1.20 $rv = $dbh->load_table(file => $fileName, tbl => $relationName);
1742 : parrello 1.10 };
1743 :     if (!defined $rv) {
1744 : parrello 1.3 $retVal->AddMessage($@) if ($@);
1745 : parrello 1.20 $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1746 : parrello 1.10 Trace("Table load failed for $relationName.") if T(1);
1747 :     } else {
1748 : parrello 1.22 # Here we successfully loaded the table.
1749 :     $retVal->Add("tables");
1750 :     my $size = -s $fileName;
1751 :     Trace("$size bytes loaded into $relationName.") if T(2);
1752 : parrello 1.10 # If we're rebuilding, we need to create the table indexes.
1753 :     if ($truncateFlag && ! $dbh->{_preIndex}) {
1754 :     eval {
1755 :     $self->CreateIndex($relationName);
1756 :     };
1757 :     if ($@) {
1758 :     $retVal->AddMessage($@);
1759 :     }
1760 :     }
1761 :     }
1762 : parrello 1.20 # Analyze the table to improve performance.
1763 : olson 1.16 $dbh->vacuum_it($relationName);
1764 : parrello 1.10 # Return the statistics.
1765 :     return $retVal;
1766 : parrello 1.1 }
1767 :    
1768 :     =head3 GenerateEntity
1769 :    
1770 : parrello 1.18 C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>
1771 : parrello 1.1
1772 :     Generate the data for a new entity instance. This method creates a field hash suitable for
1773 :     passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest
1774 :     of the fields are generated using information in the database schema.
1775 :    
1776 :     Each data type has a default algorithm for generating random test data. This can be overridden
1777 :     by including a B<DataGen> element in the field. If this happens, the content of the element is
1778 :     executed as a PERL program in the context of this module. The element may make use of a C<$this>
1779 :     variable which contains the field hash as it has been built up to the current point. If any
1780 :     fields are dependent on other fields, the C<pass> attribute can be used to control the order
1781 :     in which the fields are generated. A field with a high data pass number will be generated after
1782 :     a field with a lower one. If any external values are needed, they should be passed in via the
1783 :     optional third parameter, which will be available to the data generation script under the name
1784 :     C<$value>. Several useful utility methods are provided for generating random values, including
1785 :     L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated
1786 :     in the form of a timestamp number rather than a string.
1787 :    
1788 :     =over 4
1789 :    
1790 :     =item id
1791 :    
1792 :     ID to assign to the new entity.
1793 :    
1794 :     =item type
1795 :    
1796 :     Type name for the new entity.
1797 :    
1798 :     =item values
1799 :    
1800 :     Hash containing additional values that might be needed by the data generation methods (optional).
1801 :    
1802 :     =back
1803 :    
1804 :     =cut
1805 :    
1806 :     sub GenerateEntity {
1807 : parrello 1.10 # Get the parameters.
1808 :     my ($self, $id, $type, $values) = @_;
1809 :     # Create the return hash.
1810 :     my $this = { id => $id };
1811 :     # Get the metadata structure.
1812 :     my $metadata = $self->{_metaData};
1813 :     # Get this entity's list of fields.
1814 :     if (!exists $metadata->{Entities}->{$type}) {
1815 :     Confess("Unrecognized entity type $type in GenerateEntity.");
1816 :     } else {
1817 :     my $entity = $metadata->{Entities}->{$type};
1818 :     my $fields = $entity->{Fields};
1819 :     # Generate data from the fields.
1820 :     _GenerateFields($this, $fields, $type, $values);
1821 :     }
1822 :     # Return the hash created.
1823 :     return $this;
1824 : parrello 1.1 }
1825 :    
1826 : parrello 1.6 =head3 GetEntity
1827 :    
1828 : parrello 1.18 C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>
1829 : parrello 1.6
1830 :     Return an object describing the entity instance with a specified ID.
1831 :    
1832 :     =over 4
1833 :    
1834 :     =item entityType
1835 :    
1836 :     Entity type name.
1837 :    
1838 :     =item ID
1839 :    
1840 :     ID of the desired entity.
1841 :    
1842 :     =item RETURN
1843 :    
1844 :     Returns a B<DBObject> representing the desired entity instance, or an undefined value if no
1845 :     instance is found with the specified key.
1846 :    
1847 :     =back
1848 :    
1849 :     =cut
1850 :    
1851 :     sub GetEntity {
1852 : parrello 1.10 # Get the parameters.
1853 :     my ($self, $entityType, $ID) = @_;
1854 :     # Create a query.
1855 : parrello 1.45 my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
1856 : parrello 1.10 # Get the first (and only) object.
1857 :     my $retVal = $query->Fetch();
1858 :     # Return the result.
1859 :     return $retVal;
1860 : parrello 1.6 }
1861 :    
1862 :     =head3 GetEntityValues
1863 :    
1864 : parrello 1.18 C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>
1865 : parrello 1.6
1866 :     Return a list of values from a specified entity instance.
1867 :    
1868 :     =over 4
1869 :    
1870 :     =item entityType
1871 :    
1872 :     Entity type name.
1873 :    
1874 :     =item ID
1875 :    
1876 :     ID of the desired entity.
1877 :    
1878 :     =item fields
1879 :    
1880 :     List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
1881 :    
1882 :     =item RETURN
1883 :    
1884 :     Returns a flattened list of the values of the specified fields for the specified entity.
1885 :    
1886 :     =back
1887 :    
1888 :     =cut
1889 :    
1890 :     sub GetEntityValues {
1891 : parrello 1.10 # Get the parameters.
1892 :     my ($self, $entityType, $ID, $fields) = @_;
1893 :     # Get the specified entity.
1894 :     my $entity = $self->GetEntity($entityType, $ID);
1895 :     # Declare the return list.
1896 :     my @retVal = ();
1897 :     # If we found the entity, push the values into the return list.
1898 :     if ($entity) {
1899 :     push @retVal, $entity->Values($fields);
1900 :     }
1901 :     # Return the result.
1902 :     return @retVal;
1903 : parrello 1.6 }
1904 : parrello 1.1
1905 : parrello 1.7 =head3 GetAll
1906 :    
1907 : parrello 1.18 C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>
1908 : parrello 1.7
1909 :     Return a list of values taken from the objects returned by a query. The first three
1910 :     parameters correspond to the parameters of the L</Get> method. The final parameter is
1911 :     a list of the fields desired from each record found by the query. The field name
1912 :     syntax is the standard syntax used for fields in the B<ERDB> system--
1913 :     B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
1914 :     or relationship and I<fieldName> is the name of the field.
1915 :    
1916 :     The list returned will be a list of lists. Each element of the list will contain
1917 :     the values returned for the fields specified in the fourth parameter. If one of the
1918 :     fields specified returns multiple values, they are flattened in with the rest. For
1919 :     example, the following call will return a list of the features in a particular
1920 :     spreadsheet cell, and each feature will be represented by a list containing the
1921 :     feature ID followed by all of its aliases.
1922 :    
1923 : parrello 1.18 C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>
1924 : parrello 1.7
1925 :     =over 4
1926 :    
1927 :     =item objectNames
1928 :    
1929 :     List containing the names of the entity and relationship objects to be retrieved.
1930 :    
1931 :     =item filterClause
1932 :    
1933 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1934 :     be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1935 :     B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1936 :     parameter list as additional parameters. The fields in a filter clause can come from primary
1937 :     entity relations, relationship relations, or secondary entity relations; however, all of the
1938 :     entities and relationships involved must be included in the list of object names.
1939 :    
1940 :     =item parameterList
1941 :    
1942 :     List of the parameters to be substituted in for the parameters marks in the filter clause.
1943 :    
1944 :     =item fields
1945 :    
1946 :     List of the fields to be returned in each element of the list returned.
1947 :    
1948 :     =item count
1949 :    
1950 :     Maximum number of records to return. If omitted or 0, all available records will be returned.
1951 :    
1952 :     =item RETURN
1953 :    
1954 :     Returns a list of list references. Each element of the return list contains the values for the
1955 :     fields specified in the B<fields> parameter.
1956 :    
1957 :     =back
1958 :    
1959 :     =cut
1960 :     #: Return Type @@;
1961 :     sub GetAll {
1962 : parrello 1.10 # Get the parameters.
1963 :     my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
1964 :     # Translate the parameters from a list reference to a list. If the parameter
1965 :     # list is a scalar we convert it into a singleton list.
1966 :     my @parmList = ();
1967 :     if (ref $parameterList eq "ARRAY") {
1968 : parrello 1.45 Trace("GetAll parm list is an array.") if T(4);
1969 : parrello 1.10 @parmList = @{$parameterList};
1970 :     } else {
1971 : parrello 1.45 Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
1972 : parrello 1.10 push @parmList, $parameterList;
1973 :     }
1974 : parrello 1.30 # Insure the counter has a value.
1975 :     if (!defined $count) {
1976 :     $count = 0;
1977 :     }
1978 :     # Add the row limit to the filter clause.
1979 :     if ($count > 0) {
1980 :     $filterClause .= " LIMIT $count";
1981 :     }
1982 : parrello 1.10 # Create the query.
1983 : parrello 1.45 my $query = $self->Get($objectNames, $filterClause, \@parmList);
1984 : parrello 1.10 # Set up a counter of the number of records read.
1985 :     my $fetched = 0;
1986 :     # Loop through the records returned, extracting the fields. Note that if the
1987 :     # counter is non-zero, we stop when the number of records read hits the count.
1988 :     my @retVal = ();
1989 :     while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
1990 :     my @rowData = $row->Values($fields);
1991 :     push @retVal, \@rowData;
1992 :     $fetched++;
1993 :     }
1994 :     # Return the resulting list.
1995 :     return @retVal;
1996 : parrello 1.7 }
1997 :    
1998 : parrello 1.18 =head3 EstimateRowSize
1999 :    
2000 :     C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
2001 :    
2002 :     Estimate the row size of the specified relation. The estimated row size is computed by adding
2003 :     up the average length for each data type.
2004 :    
2005 :     =over 4
2006 :    
2007 :     =item relName
2008 :    
2009 :     Name of the relation whose estimated row size is desired.
2010 :    
2011 :     =item RETURN
2012 :    
2013 :     Returns an estimate of the row size for the specified relation.
2014 :    
2015 :     =back
2016 :    
2017 :     =cut
2018 :     #: Return Type $;
2019 :     sub EstimateRowSize {
2020 :     # Get the parameters.
2021 :     my ($self, $relName) = @_;
2022 :     # Declare the return variable.
2023 :     my $retVal = 0;
2024 :     # Find the relation descriptor.
2025 :     my $relation = $self->_FindRelation($relName);
2026 :     # Get the list of fields.
2027 :     for my $fieldData (@{$relation->{Fields}}) {
2028 :     # Get the field type and add its length.
2029 :     my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
2030 :     $retVal += $fieldLen;
2031 :     }
2032 :     # Return the result.
2033 :     return $retVal;
2034 :     }
2035 :    
2036 : parrello 1.38 =head3 GetFieldTable
2037 :    
2038 :     C<< my $fieldHash = $self->GetFieldTable($objectnName); >>
2039 :    
2040 :     Get the field structure for a specified entity or relationship.
2041 :    
2042 :     =over 4
2043 :    
2044 :     =item objectName
2045 :    
2046 :     Name of the desired entity or relationship.
2047 :    
2048 :     =item RETURN
2049 :    
2050 :     The table containing the field descriptors for the specified object.
2051 :    
2052 :     =back
2053 :    
2054 :     =cut
2055 :    
2056 :     sub GetFieldTable {
2057 :     # Get the parameters.
2058 :     my ($self, $objectName) = @_;
2059 :     # Get the descriptor from the metadata.
2060 :     my $objectData = $self->_GetStructure($objectName);
2061 :     # Return the object's field table.
2062 :     return $objectData->{Fields};
2063 :     }
2064 :    
2065 :     =head3 GetUsefulCrossValues
2066 :    
2067 :     C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
2068 :    
2069 :     Return a list of the useful attributes that would be returned by a B<Cross> call
2070 :     from an entity of the source entity type through the specified relationship. This
2071 :     means it will return the fields of the target entity type and the intersection data
2072 :     fields in the relationship. Only primary table fields are returned. In other words,
2073 :     the field names returned will be for fields where there is always one and only one
2074 :     value.
2075 :    
2076 :     =over 4
2077 :    
2078 :     =item sourceEntity
2079 :    
2080 :     Name of the entity from which the relationship crossing will start.
2081 :    
2082 :     =item relationship
2083 :    
2084 :     Name of the relationship being crossed.
2085 :    
2086 :     =item RETURN
2087 :    
2088 :     Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.
2089 :    
2090 :     =back
2091 :    
2092 :     =cut
2093 :     #: Return Type @;
2094 :     sub GetUsefulCrossValues {
2095 :     # Get the parameters.
2096 :     my ($self, $sourceEntity, $relationship) = @_;
2097 :     # Declare the return variable.
2098 :     my @retVal = ();
2099 :     # Determine the target entity for the relationship. This is whichever entity is not
2100 :     # the source entity. So, if the source entity is the FROM, we'll get the name of
2101 :     # the TO, and vice versa.
2102 :     my $relStructure = $self->_GetStructure($relationship);
2103 :     my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");
2104 :     my $targetEntity = $relStructure->{$targetEntityType};
2105 :     # Get the field table for the entity.
2106 :     my $entityFields = $self->GetFieldTable($targetEntity);
2107 :     # The field table is a hash. The hash key is the field name. The hash value is a structure.
2108 :     # For the entity fields, the key aspect of the target structure is that the {relation} value
2109 :     # must match the entity name.
2110 :     my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }
2111 :     keys %{$entityFields};
2112 :     # Push the fields found onto the return variable.
2113 :     push @retVal, sort @fieldList;
2114 :     # Get the field table for the relationship.
2115 :     my $relationshipFields = $self->GetFieldTable($relationship);
2116 :     # Here we have a different rule. We want all the fields other than "from-link" and "to-link".
2117 :     # This may end up being an empty set.
2118 :     my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }
2119 :     keys %{$relationshipFields};
2120 :     # Push these onto the return list.
2121 :     push @retVal, sort @fieldList2;
2122 :     # Return the result.
2123 :     return @retVal;
2124 :     }
2125 :    
2126 : parrello 1.1 =head2 Internal Utility Methods
2127 :    
2128 : parrello 1.45 =head3 SetupSQL
2129 :    
2130 :     Process a list of object names and a filter clause so that they can be used to
2131 :     build an SQL statement. This method takes in a reference to a list of object names
2132 :     and a filter clause. It will return a corrected filter clause, a list of mapped
2133 :     names and the mapped name hash.
2134 :    
2135 :     This is an instance method.
2136 :    
2137 :     =over 4
2138 :    
2139 :     =item objectNames
2140 :    
2141 :     Reference to a list of the object names to be included in the query.
2142 :    
2143 :     =item filterClause
2144 :    
2145 :     A string containing the WHERE clause for the query (without the C<WHERE>) and also
2146 :     optionally the C<ORDER BY> and C<LIMIT> clauses.
2147 :    
2148 :     =item RETURN
2149 :    
2150 :     Returns a three-element list. The first element is the SQL statement suffix, beginning
2151 :     with the FROM clause. The second element is a reference to a list of the names to be
2152 :     used in retrieving the fields. The third element is a hash mapping the names to the
2153 :     objects they represent.
2154 :    
2155 :     =back
2156 :    
2157 :     =cut
2158 :    
2159 :     sub _SetupSQL {
2160 :     my ($self, $objectNames, $filterClause) = @_;
2161 :     # Adjust the list of object names to account for multiple occurrences of the
2162 :     # same object. We start with a hash table keyed on object name that will
2163 :     # return the object suffix. The first time an object is encountered it will
2164 :     # not be found in the hash. The next time the hash will map the object name
2165 :     # to 2, then 3, and so forth.
2166 :     my %objectHash = ();
2167 :     # This list will contain the object names as they are to appear in the
2168 :     # FROM list.
2169 :     my @fromList = ();
2170 :     # This list contains the suffixed object name for each object. It is exactly
2171 :     # parallel to the list in the $objectNames parameter.
2172 :     my @mappedNameList = ();
2173 :     # Finally, this hash translates from a mapped name to its original object name.
2174 :     my %mappedNameHash = ();
2175 :     # Now we create the lists. Note that for every single name we push something into
2176 :     # @fromList and @mappedNameList. This insures that those two arrays are exactly
2177 :     # parallel to $objectNames.
2178 :     for my $objectName (@{$objectNames}) {
2179 :     # Get the next suffix for this object.
2180 :     my $suffix = $objectHash{$objectName};
2181 :     if (! $suffix) {
2182 :     # Here we are seeing the object for the first time. The object name
2183 :     # is used as is.
2184 :     push @mappedNameList, $objectName;
2185 :     push @fromList, $objectName;
2186 :     $mappedNameHash{$objectName} = $objectName;
2187 :     # Denote the next suffix will be 2.
2188 :     $objectHash{$objectName} = 2;
2189 :     } else {
2190 :     # Here we've seen the object before. We construct a new name using
2191 :     # the suffix from the hash and update the hash.
2192 :     my $mappedName = "$objectName$suffix";
2193 :     $objectHash{$objectName} = $suffix + 1;
2194 :     # The FROM list has the object name followed by the mapped name. This
2195 :     # tells SQL it's still the same table, but we're using a different name
2196 :     # for it to avoid confusion.
2197 :     push @fromList, "$objectName $mappedName";
2198 :     # The mapped-name list contains the real mapped name.
2199 :     push @mappedNameList, $mappedName;
2200 :     # Finally, enable us to get back from the mapped name to the object name.
2201 :     $mappedNameHash{$mappedName} = $objectName;
2202 :     }
2203 :     }
2204 :     # Begin the SELECT suffix. It starts with
2205 :     #
2206 :     # FROM name1, name2, ... nameN
2207 :     #
2208 :     my $suffix = "FROM " . join(', ', @fromList);
2209 :     # Check for a filter clause.
2210 :     if ($filterClause) {
2211 :     # Here we have one, so we convert its field names and add it to the query. First,
2212 :     # We create a copy of the filter string we can work with.
2213 :     my $filterString = $filterClause;
2214 :     # Next, we sort the object names by length. This helps protect us from finding
2215 :     # object names inside other object names when we're doing our search and replace.
2216 :     my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2217 :     # We will also keep a list of conditions to add to the WHERE clause in order to link
2218 :     # entities and relationships as well as primary relations to secondary ones.
2219 :     my @joinWhere = ();
2220 :     # The final preparatory step is to create a hash table of relation names. The
2221 :     # table begins with the relation names already in the SELECT command. We may
2222 :     # need to add relations later if there is filtering on a field in a secondary
2223 :     # relation. The secondary relations are the ones that contain multiply-
2224 :     # occurring or optional fields.
2225 :     my %fromNames = map { $_ => 1 } @sortedNames;
2226 :     # We are ready to begin. We loop through the object names, replacing each
2227 :     # object name's field references by the corresponding SQL field reference.
2228 :     # Along the way, if we find a secondary relation, we will need to add it
2229 :     # to the FROM clause.
2230 :     for my $mappedName (@sortedNames) {
2231 :     # Get the length of the object name plus 2. This is the value we add to the
2232 :     # size of the field name to determine the size of the field reference as a
2233 :     # whole.
2234 :     my $nameLength = 2 + length $mappedName;
2235 :     # Get the real object name for this mapped name.
2236 :     my $objectName = $mappedNameHash{$mappedName};
2237 :     Trace("Processing $mappedName for object $objectName.") if T(4);
2238 :     # Get the object's field list.
2239 :     my $fieldList = $self->GetFieldTable($objectName);
2240 :     # Find the field references for this object.
2241 :     while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2242 :     # At this point, $1 contains the field name, and the current position
2243 :     # is set immediately after the final parenthesis. We pull out the name of
2244 :     # the field and the position and length of the field reference as a whole.
2245 :     my $fieldName = $1;
2246 :     my $len = $nameLength + length $fieldName;
2247 :     my $pos = pos($filterString) - $len;
2248 :     # Insure the field exists.
2249 :     if (!exists $fieldList->{$fieldName}) {
2250 :     Confess("Field $fieldName not found for object $objectName.");
2251 :     } else {
2252 :     Trace("Processing $fieldName at position $pos.") if T(4);
2253 :     # Get the field's relation.
2254 :     my $relationName = $fieldList->{$fieldName}->{relation};
2255 :     # Now we have a secondary relation. We need to insure it matches the
2256 :     # mapped name of the primary relation. First we peel off the suffix
2257 :     # from the mapped name.
2258 :     my $mappingSuffix = substr $mappedName, length($objectName);
2259 :     # Put the mapping suffix onto the relation name to get the
2260 :     # mapped relation name.
2261 :     my $mappedRelationName = "$relationName$mappingSuffix";
2262 :     # Insure the relation is in the FROM clause.
2263 :     if (!exists $fromNames{$mappedRelationName}) {
2264 :     # Add the relation to the FROM clause.
2265 :     if ($mappedRelationName eq $relationName) {
2266 :     # The name is un-mapped, so we add it without
2267 :     # any frills.
2268 :     $suffix .= ", $relationName";
2269 :     push @joinWhere, "$objectName.id = $relationName.id";
2270 :     } else {
2271 :     # Here we have a mapping situation.
2272 :     $suffix .= ", $relationName $mappedRelationName";
2273 :     push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2274 :     }
2275 :     # Denote we have this relation available for future fields.
2276 :     $fromNames{$mappedRelationName} = 1;
2277 :     }
2278 :     # Form an SQL field reference from the relation name and the field name.
2279 :     my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2280 :     # Put it into the filter string in place of the old value.
2281 :     substr($filterString, $pos, $len) = $sqlReference;
2282 :     # Reposition the search.
2283 :     pos $filterString = $pos + length $sqlReference;
2284 :     }
2285 :     }
2286 :     }
2287 :     # The next step is to join the objects together. We only need to do this if there
2288 :     # is more than one object in the object list. We start with the first object and
2289 :     # run through the objects after it. Note also that we make a safety copy of the
2290 :     # list before running through it.
2291 :     my @mappedObjectList = @mappedNameList;
2292 :     my $lastMappedObject = shift @mappedObjectList;
2293 :     # Get the join table.
2294 :     my $joinTable = $self->{_metaData}->{Joins};
2295 :     # Loop through the object list.
2296 :     for my $thisMappedObject (@mappedObjectList) {
2297 :     # Look for a join using the real object names.
2298 :     my $lastObject = $mappedNameHash{$lastMappedObject};
2299 :     my $thisObject = $mappedNameHash{$thisMappedObject};
2300 :     my $joinKey = "$lastObject/$thisObject";
2301 :     if (!exists $joinTable->{$joinKey}) {
2302 :     # Here there's no join, so we throw an error.
2303 :     Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2304 :     } else {
2305 :     # Get the join clause.
2306 :     my $unMappedJoin = $joinTable->{$joinKey};
2307 :     # Fix the names.
2308 :     $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2309 :     $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2310 :     push @joinWhere, $unMappedJoin;
2311 :     # Save this object as the last object for the next iteration.
2312 :     $lastMappedObject = $thisMappedObject;
2313 :     }
2314 :     }
2315 :     # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2316 :     # here is we want the filter clause to be empty if there's no WHERE filter.
2317 :     # We'll put the ORDER BY / LIMIT clauses in the following variable.
2318 :     my $orderClause = "";
2319 :     # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2320 :     # operator so that we find the first occurrence of either verb.
2321 :     if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2322 :     # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2323 :     my $pos = pos $filterString;
2324 :     $orderClause = $2 . substr($filterString, $pos);
2325 :     $filterString = $1;
2326 :     }
2327 :     # Add the filter and the join clauses (if any) to the SELECT command.
2328 :     if ($filterString) {
2329 :     Trace("Filter string is \"$filterString\".") if T(4);
2330 :     push @joinWhere, "($filterString)";
2331 :     }
2332 :     if (@joinWhere) {
2333 :     $suffix .= " WHERE " . join(' AND ', @joinWhere);
2334 :     }
2335 :     # Add the sort or limit clause (if any) to the SELECT command.
2336 :     if ($orderClause) {
2337 :     $suffix .= " $orderClause";
2338 :     }
2339 :     }
2340 :     # Return the suffix, the mapped name list, and the mapped name hash.
2341 :     return ($suffix, \@mappedNameList, \%mappedNameHash);
2342 :     }
2343 :    
2344 :     =head3 GetStatementHandle
2345 :    
2346 :     This method will prepare and execute an SQL query, returning the statement handle.
2347 :     The main reason for doing this here is so that everybody who does SQL queries gets
2348 :     the benefit of tracing.
2349 :    
2350 :     This is an instance method.
2351 :    
2352 :     =over 4
2353 :    
2354 :     =item command
2355 :    
2356 :     Command to prepare and execute.
2357 :    
2358 :     =item params
2359 :    
2360 :     Reference to a list of the values to be substituted in for the parameter marks.
2361 :    
2362 :     =item RETURN
2363 :    
2364 :     Returns a prepared and executed statement handle from which the caller can extract
2365 :     results.
2366 :    
2367 :     =back
2368 :    
2369 :     =cut
2370 :    
2371 :     sub _GetStatementHandle {
2372 :     # Get the parameters.
2373 :     my ($self, $command, $params) = @_;
2374 :     # Trace the query.
2375 :     Trace("SQL query: $command") if T(SQL => 3);
2376 :     Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2377 :     # Get the database handle.
2378 :     my $dbh = $self->{_dbh};
2379 :     # Prepare the command.
2380 :     my $sth = $dbh->prepare_command($command);
2381 :     # Execute it with the parameters bound in.
2382 :     $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2383 :     # Return the statement handle.
2384 :     return $sth;
2385 :     }
2386 :    
2387 : parrello 1.1 =head3 GetLoadStats
2388 :    
2389 :     Return a blank statistics object for use by the load methods.
2390 :    
2391 :     This is a static method.
2392 :    
2393 :     =cut
2394 :    
2395 : parrello 1.29 sub _GetLoadStats{
2396 : parrello 1.28 return Stats->new();
2397 : parrello 1.1 }
2398 :    
2399 :     =head3 GenerateFields
2400 :    
2401 :     Generate field values from a field structure and store in a specified table. The field names
2402 :     are first sorted by pass count, certain pre-defined fields are removed from the list, and
2403 :     then we rip through them evaluation the data generation string. Fields in the primary relation
2404 :     are stored as scalars; fields in secondary relations are stored as value lists.
2405 :    
2406 :     This is a static method.
2407 :    
2408 :     =over 4
2409 :    
2410 :     =item this
2411 :    
2412 :     Hash table into which the field values should be placed.
2413 :    
2414 :     =item fields
2415 :    
2416 :     Field structure from which the field descriptors should be taken.
2417 :    
2418 :     =item type
2419 :    
2420 :     Type name of the object whose fields are being generated.
2421 :    
2422 :     =item values (optional)
2423 :    
2424 :     Reference to a value structure from which additional values can be taken.
2425 :    
2426 :     =item from (optiona)
2427 :    
2428 :     Reference to the source entity instance if relationship data is being generated.
2429 :    
2430 :     =item to (optional)
2431 :    
2432 :     Reference to the target entity instance if relationship data is being generated.
2433 :    
2434 :     =back
2435 :    
2436 :     =cut
2437 :    
2438 :     sub _GenerateFields {
2439 : parrello 1.10 # Get the parameters.
2440 :     my ($this, $fields, $type, $values, $from, $to) = @_;
2441 :     # Sort the field names by pass number.
2442 :     my @fieldNames = sort { $fields->{$a}->{DataGen}->{pass} <=> $fields->{$b}->{DataGen}->{pass} } keys %{$fields};
2443 :     # Loop through the field names, generating data.
2444 :     for my $name (@fieldNames) {
2445 :     # Only proceed if this field needs to be generated.
2446 :     if (!exists $this->{$name}) {
2447 :     # Get this field's data generation descriptor.
2448 :     my $fieldDescriptor = $fields->{$name};
2449 :     my $data = $fieldDescriptor->{DataGen};
2450 :     # Get the code to generate the field value.
2451 :     my $codeString = $data->{content};
2452 :     # Determine whether or not this field is in the primary relation.
2453 :     if ($fieldDescriptor->{relation} eq $type) {
2454 :     # Here we have a primary relation field. Store the field value as
2455 :     # a scalar.
2456 :     $this->{$name} = eval($codeString);
2457 :     } else {
2458 :     # Here we have a secondary relation field. Create a null list
2459 :     # and push the desired number of field values onto it.
2460 :     my @fieldValues = ();
2461 :     my $count = IntGen(0,$data->{testCount});
2462 :     for (my $i = 0; $i < $count; $i++) {
2463 :     my $newValue = eval($codeString);
2464 :     push @fieldValues, $newValue;
2465 :     }
2466 :     # Store the value list in the main hash.
2467 :     $this->{$name} = \@fieldValues;
2468 :     }
2469 :     }
2470 :     }
2471 : parrello 1.1 }
2472 :    
2473 :     =head3 DumpRelation
2474 :    
2475 :     Dump the specified relation's to the specified output file in tab-delimited format.
2476 :    
2477 :     This is an instance method.
2478 :    
2479 :     =over 4
2480 :    
2481 :     =item outputDirectory
2482 :    
2483 :     Directory to contain the output file.
2484 :    
2485 :     =item relationName
2486 :    
2487 :     Name of the relation to dump.
2488 :    
2489 :     =item relation
2490 :    
2491 :     Structure describing the relation to be dumped.
2492 :    
2493 :     =back
2494 :    
2495 :     =cut
2496 :    
2497 :     sub _DumpRelation {
2498 : parrello 1.10 # Get the parameters.
2499 :     my ($self, $outputDirectory, $relationName, $relation) = @_;
2500 :     # Open the output file.
2501 :     my $fileName = "$outputDirectory/$relationName.dtx";
2502 :     open(DTXOUT, ">$fileName") || Confess("Could not open dump file $fileName: $!");
2503 :     # Create a query for the specified relation.
2504 :     my $dbh = $self->{_dbh};
2505 :     my $query = $dbh->prepare_command("SELECT * FROM $relationName");
2506 :     # Execute the query.
2507 :     $query->execute() || Confess("SELECT error dumping $relationName.");
2508 :     # Loop through the results.
2509 :     while (my @row = $query->fetchrow) {
2510 :     # Escape any tabs or new-lines in the row text.
2511 :     for my $field (@row) {
2512 :     $field =~ s/\n/\\n/g;
2513 :     $field =~ s/\t/\\t/g;
2514 :     }
2515 :     # Tab-join the row and write it to the output file.
2516 :     my $rowText = join("\t", @row);
2517 :     print DTXOUT "$rowText\n";
2518 :     }
2519 :     # Close the output file.
2520 :     close DTXOUT;
2521 : parrello 1.1 }
2522 :    
2523 :     =head3 GetStructure
2524 :    
2525 :     Get the data structure for a specified entity or relationship.
2526 :    
2527 :     This is an instance method.
2528 :    
2529 :     =over 4
2530 :    
2531 :     =item objectName
2532 :    
2533 :     Name of the desired entity or relationship.
2534 :    
2535 :     =item RETURN
2536 :    
2537 :     The descriptor for the specified object.
2538 :    
2539 :     =back
2540 :    
2541 :     =cut
2542 :    
2543 :     sub _GetStructure {
2544 : parrello 1.10 # Get the parameters.
2545 :     my ($self, $objectName) = @_;
2546 :     # Get the metadata structure.
2547 :     my $metadata = $self->{_metaData};
2548 :     # Declare the variable to receive the descriptor.
2549 :     my $retVal;
2550 :     # Get the descriptor from the metadata.
2551 :     if (exists $metadata->{Entities}->{$objectName}) {
2552 :     $retVal = $metadata->{Entities}->{$objectName};
2553 :     } elsif (exists $metadata->{Relationships}->{$objectName}) {
2554 :     $retVal = $metadata->{Relationships}->{$objectName};
2555 :     } else {
2556 :     Confess("Object $objectName not found in database.");
2557 :     }
2558 :     # Return the descriptor.
2559 :     return $retVal;
2560 : parrello 1.1 }
2561 :    
2562 :     =head3 GetRelationTable
2563 :    
2564 :     Get the list of relations for a specified entity or relationship.
2565 :    
2566 :     This is an instance method.
2567 :    
2568 :     =over 4
2569 :    
2570 :     =item objectName
2571 :    
2572 :     Name of the desired entity or relationship.
2573 :    
2574 :     =item RETURN
2575 :    
2576 :     A table containing the relations for the specified object.
2577 :    
2578 :     =back
2579 :    
2580 :     =cut
2581 :    
2582 :     sub _GetRelationTable {
2583 : parrello 1.10 # Get the parameters.
2584 :     my ($self, $objectName) = @_;
2585 :     # Get the descriptor from the metadata.
2586 :     my $objectData = $self->_GetStructure($objectName);
2587 :     # Return the object's relation list.
2588 :     return $objectData->{Relations};
2589 : parrello 1.1 }
2590 :    
2591 :     =head3 ValidateFieldNames
2592 :    
2593 :     Determine whether or not the field names are valid. A description of the problems with the names
2594 :     will be written to the standard error output. If there is an error, this method will abort. This is
2595 :     a static method.
2596 :    
2597 :     =over 4
2598 :    
2599 :     =item metadata
2600 :    
2601 :     Metadata structure loaded from the XML data definition.
2602 :    
2603 :     =back
2604 :    
2605 :     =cut
2606 :    
2607 :     sub _ValidateFieldNames {
2608 : parrello 1.10 # Get the object.
2609 :     my ($metadata) = @_;
2610 :     # Declare the return value. We assume success.
2611 :     my $retVal = 1;
2612 :     # Loop through the sections of the database definition.
2613 :     for my $section ('Entities', 'Relationships') {
2614 :     # Loop through the objects in this section.
2615 :     for my $object (values %{$metadata->{$section}}) {
2616 :     # Loop through the object's fields.
2617 :     for my $fieldName (keys %{$object->{Fields}}) {
2618 :     # Now we make some initial validations.
2619 :     if ($fieldName =~ /--/) {
2620 :     # Here we have a doubled minus sign.
2621 :     print STDERR "Field name $fieldName has a doubled hyphen.\n";
2622 :     $retVal = 0;
2623 :     } elsif ($fieldName !~ /^[A-Za-z]/) {
2624 :     # Here the field name is missing the initial letter.
2625 :     print STDERR "Field name $fieldName does not begin with a letter.\n";
2626 :     $retVal = 0;
2627 :     } else {
2628 :     # Strip out the minus signs. Everything remaining must be a letter
2629 :     # or digit.
2630 :     my $strippedName = $fieldName;
2631 :     $strippedName =~ s/-//g;
2632 :     if ($strippedName !~ /^[A-Za-z0-9]+$/) {
2633 :     print STDERR "Field name $fieldName contains illegal characters.\n";
2634 :     $retVal = 0;
2635 :     }
2636 :     }
2637 :     }
2638 :     }
2639 :     }
2640 :     # If an error was found, fail.
2641 :     if ($retVal == 0) {
2642 :     Confess("Errors found in field names.");
2643 :     }
2644 : parrello 1.1 }
2645 :    
2646 :     =head3 LoadRelation
2647 :    
2648 :     Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk
2649 :     file with the same name as the relation exists in the specified directory.
2650 :    
2651 :     This is an instance method.
2652 :    
2653 :     =over 4
2654 :    
2655 :     =item dbh
2656 :    
2657 :     DBKernel object for accessing the database.
2658 :    
2659 :     =item directoryName
2660 :    
2661 :     Name of the directory containing the tab-delimited data files.
2662 :    
2663 :     =item relationName
2664 :    
2665 :     Name of the relation to load.
2666 :    
2667 :     =item rebuild
2668 :    
2669 :     TRUE if the table should be dropped and re-created before loading.
2670 :    
2671 :     =item RETURN
2672 :    
2673 :     Returns a statistical object describing the number of records read and a list of error messages.
2674 :    
2675 :     =back
2676 :    
2677 :     =cut
2678 :    
2679 :     sub _LoadRelation {
2680 : parrello 1.10 # Get the parameters.
2681 :     my ($self, $directoryName, $relationName, $rebuild) = @_;
2682 :     # Create the file name.
2683 :     my $fileName = "$directoryName/$relationName";
2684 :     # If the file doesn't exist, try adding the .dtx suffix.
2685 :     if (! -e $fileName) {
2686 :     $fileName .= ".dtx";
2687 :     if (! -e $fileName) {
2688 :     $fileName = "";
2689 :     }
2690 :     }
2691 :     # Create the return object.
2692 :     my $retVal = _GetLoadStats();
2693 :     # If a file exists to load the table, its name will be in $fileName. Otherwise, $fileName will
2694 :     # be a null string.
2695 :     if ($fileName ne "") {
2696 :     # Load the relation from the file.
2697 :     $retVal = $self->LoadTable($fileName, $relationName, $rebuild);
2698 :     } elsif ($rebuild) {
2699 :     # Here we are rebuilding, but no file exists, so we just re-create the table.
2700 :     $self->CreateTable($relationName, 1);
2701 :     }
2702 :     # Return the statistics from the load.
2703 :     return $retVal;
2704 : parrello 1.1 }
2705 :    
2706 :     =head3 LoadMetaData
2707 :    
2708 :     This method loads the data describing this database from an XML file into a metadata structure.
2709 :     The resulting structure is a set of nested hash tables containing all the information needed to
2710 :     load or use the database. The schema for the XML file is F<ERDatabase.xml>.
2711 :    
2712 :     This is a static method.
2713 :    
2714 :     =over 4
2715 :    
2716 :     =item filename
2717 :    
2718 :     Name of the file containing the database definition.
2719 :    
2720 :     =item RETURN
2721 :    
2722 :     Returns a structure describing the database.
2723 :    
2724 :     =back
2725 :    
2726 :     =cut
2727 :    
2728 :     sub _LoadMetaData {
2729 : parrello 1.10 # Get the parameters.
2730 :     my ($filename) = @_;
2731 : parrello 1.15 Trace("Reading Sprout DBD from $filename.") if T(2);
2732 : parrello 1.10 # Slurp the XML file into a variable. Extensive use of options is used to insure we
2733 :     # get the exact structure we want.
2734 :     my $metadata = XML::Simple::XMLin($filename,
2735 :     GroupTags => { Relationships => 'Relationship',
2736 :     Entities => 'Entity',
2737 :     Fields => 'Field',
2738 :     Indexes => 'Index',
2739 :     IndexFields => 'IndexField'},
2740 :     KeyAttr => { Relationship => 'name',
2741 :     Entity => 'name',
2742 :     Field => 'name'},
2743 :     ForceArray => ['Field', 'Index', 'IndexField'],
2744 :     ForceContent => 1,
2745 :     NormalizeSpace => 2
2746 :     );
2747 :     Trace("XML metadata loaded from file $filename.") if T(1);
2748 :     # Before we go any farther, we need to validate the field and object names. If an error is found,
2749 :     # the method below will fail.
2750 :     _ValidateFieldNames($metadata);
2751 :     # Next we need to create a hash table for finding relations. The entities and relationships are
2752 :     # implemented as one or more database relations.
2753 :     my %masterRelationTable = ();
2754 :     # Loop through the entities.
2755 :     my $entityList = $metadata->{Entities};
2756 :     for my $entityName (keys %{$entityList}) {
2757 :     my $entityStructure = $entityList->{$entityName};
2758 :     #
2759 : parrello 1.12 # The first step is to create all the entity's default values. For C<Field> elements,
2760 : parrello 1.10 # the relation name must be added where it is not specified. For relationships,
2761 :     # the B<from-link> and B<to-link> fields must be inserted, and for entities an B<id>
2762 :     # field must be added to each relation. Finally, each field will have a C<PrettySort> attribute
2763 :     # added that can be used to pull the implicit fields to the top when displaying the field
2764 :     # documentation. The PrettySort values are 1-based and indicate in which pass through a
2765 :     # relation's data the field should be displayed-- 1 for the first pass, 2 for the second,
2766 :     # and so on.
2767 :     #
2768 :     # Fix up this entity.
2769 :     _FixupFields($entityStructure, $entityName, 2, 3);
2770 :     # Add the ID field.
2771 :     _AddField($entityStructure, 'id', { type => $entityStructure->{keyType},
2772 :     relation => $entityName,
2773 :     Notes => { content => "Unique identifier for this \[b\]$entityName\[/b\]." },
2774 :     PrettySort => 1});
2775 :     #
2776 :     # The current field list enables us to quickly find the relation containing a particular field.
2777 :     # We also need a list that tells us the fields in each relation. We do this by creating a
2778 :     # Relations structure in the entity structure and collating the fields into it based on their
2779 :     # C<relation> property. There is one tricky bit, which is that every relation has to have the
2780 :     # C<id> field in it. Note also that the field list is put into a C<Fields> member of the
2781 :     # relation's structure so that it looks more like the entity and relationship structures.
2782 :     #
2783 :     # First we need to create the relations list.
2784 :     my $relationTable = { };
2785 :     # Loop through the fields. We use a list of field names to prevent a problem with
2786 :     # the hash table cursor losing its place during the loop.
2787 :     my $fieldList = $entityStructure->{Fields};
2788 :     my @fieldNames = keys %{$fieldList};
2789 :     for my $fieldName (@fieldNames) {
2790 :     my $fieldData = $fieldList->{$fieldName};
2791 :     # Get the current field's relation name.
2792 :     my $relationName = $fieldData->{relation};
2793 :     # Insure the relation exists.
2794 :     if (!exists $relationTable->{$relationName}) {
2795 :     $relationTable->{$relationName} = { Fields => { } };
2796 :     }
2797 :     # Add the field to the relation's field structure.
2798 :     $relationTable->{$relationName}->{Fields}->{$fieldName} = $fieldData;
2799 :     }
2800 :     # Now that we've organized all our fields by relation name we need to do some serious
2801 :     # housekeeping. We must add the C<id> field to every relation and convert each relation
2802 :     # to a list of fields. First, we need the ID field itself.
2803 :     my $idField = $fieldList->{id};
2804 :     # Loop through the relations.
2805 :     for my $relationName (keys %{$relationTable}) {
2806 :     my $relation = $relationTable->{$relationName};
2807 :     # Get the relation's field list.
2808 :     my $relationFieldList = $relation->{Fields};
2809 :     # Add the ID field to it. If the field's already there, it will not make any
2810 :     # difference.
2811 :     $relationFieldList->{id} = $idField;
2812 :     # Convert the field set from a hash into a list using the pretty-sort number.
2813 :     $relation->{Fields} = _ReOrderRelationTable($relationFieldList);
2814 :     # Add the relation to the master table.
2815 :     $masterRelationTable{$relationName} = $relation;
2816 :     }
2817 :     # The indexes come next. The primary relation will have a unique-keyed index based on the ID field.
2818 :     # The other relations must have at least one index that begins with the ID field. In addition, the
2819 :     # metadata may require alternate indexes. We do those alternate indexes first. To begin, we need to
2820 :     # get the entity's field list and index list.
2821 :     my $indexList = $entityStructure->{Indexes};
2822 :     # Loop through the indexes.
2823 :     for my $indexData (@{$indexList}) {
2824 :     # We need to find this index's fields. All of them should belong to the same relation.
2825 :     # The ID field is an exception, since it's in all relations.
2826 :     my $relationName = '0';
2827 :     for my $fieldDescriptor (@{$indexData->{IndexFields}}) {
2828 :     # Get this field's name.
2829 :     my $fieldName = $fieldDescriptor->{name};
2830 :     # Only proceed if it is NOT the ID field.
2831 :     if ($fieldName ne 'id') {
2832 :     # Find the relation containing the current index field.
2833 :     my $thisName = $fieldList->{$fieldName}->{relation};
2834 :     if ($relationName eq '0') {
2835 :     # Here we're looking at the first field, so we save its relation name.
2836 :     $relationName = $thisName;
2837 :     } elsif ($relationName ne $thisName) {
2838 :     # Here we have a field mismatch.
2839 :     Confess("Mixed index: field $fieldName does not belong to relation $relationName.");
2840 :     }
2841 :     }
2842 :     }
2843 :     # Now $relationName is the name of the relation that contains this index. Add the index structure
2844 :     # to the relation.
2845 :     push @{$relationTable->{$relationName}->{Indexes}}, $indexData;
2846 :     }
2847 :     # Now each index has been put in a relation. We need to add the primary index for the primary
2848 :     # relation.
2849 :     push @{$relationTable->{$entityName}->{Indexes}},
2850 :     { IndexFields => [ {name => 'id', order => 'ascending'} ], Unique => 'true',
2851 :     Notes => { content => "Primary index for $entityName." }
2852 :     };
2853 :     # The next step is to insure that each relation has at least one index that begins with the ID field.
2854 :     # After that, we convert each relation's index list to an index table. We first need to loop through
2855 :     # the relations.
2856 :     for my $relationName (keys %{$relationTable}) {
2857 :     my $relation = $relationTable->{$relationName};
2858 :     # Get the relation's index list.
2859 :     my $indexList = $relation->{Indexes};
2860 :     # Insure this relation has an ID index.
2861 :     my $found = 0;
2862 :     for my $index (@{$indexList}) {
2863 :     if ($index->{IndexFields}->[0]->{name} eq "id") {
2864 :     $found = 1;
2865 :     }
2866 :     }
2867 :     if ($found == 0) {
2868 :     push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
2869 :     }
2870 :     # Now we need to convert the relation's index list to an index table. We begin by creating
2871 :     # an empty table in the relation structure.
2872 :     $relation->{Indexes} = { };
2873 :     # Loop through the indexes.
2874 :     my $count = 0;
2875 :     for my $index (@{$indexList}) {
2876 :     # Add this index to the index table.
2877 :     _AddIndex("idx$relationName$count", $relation, $index);
2878 :     # Increment the counter so that the next index has a different name.
2879 :     $count++;
2880 :     }
2881 :     }
2882 :     # Finally, we add the relation structure to the entity.
2883 :     $entityStructure->{Relations} = $relationTable;
2884 :     }
2885 :     # Loop through the relationships. Relationships actually turn out to be much simpler than entities.
2886 :     # For one thing, there is only a single constituent relation.
2887 :     my $relationshipList = $metadata->{Relationships};
2888 :     for my $relationshipName (keys %{$relationshipList}) {
2889 :     my $relationshipStructure = $relationshipList->{$relationshipName};
2890 :     # Fix up this relationship.
2891 :     _FixupFields($relationshipStructure, $relationshipName, 2, 3);
2892 :     # Format a description for the FROM field.
2893 :     my $fromEntity = $relationshipStructure->{from};
2894 :     my $fromComment = "<b>id</b> of the source <b><a href=\"#$fromEntity\">$fromEntity</a></b>.";
2895 :     # Get the FROM entity's key type.
2896 :     my $fromType = $entityList->{$fromEntity}->{keyType};
2897 :     # Add the FROM field.
2898 :     _AddField($relationshipStructure, 'from-link', { type => $fromType,
2899 :     relation => $relationshipName,
2900 :     Notes => { content => $fromComment },
2901 :     PrettySort => 1});
2902 :     # Format a description for the TO field.
2903 :     my $toEntity = $relationshipStructure->{to};
2904 :     my $toComment = "<b>id</b> of the target <b><a href=\"#$toEntity\">$toEntity</a></b>.";
2905 :     # Get the TO entity's key type.
2906 :     my $toType = $entityList->{$toEntity}->{keyType};
2907 :     # Add the TO field.
2908 :     _AddField($relationshipStructure, 'to-link', { type=> $toType,
2909 :     relation => $relationshipName,
2910 :     Notes => { content => $toComment },
2911 :     PrettySort => 1});
2912 :     # Create an index-free relation from the fields.
2913 :     my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
2914 :     Indexes => { } };
2915 :     $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
2916 :     # Create the FROM and TO indexes.
2917 :     _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
2918 :     _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
2919 :     # Add the relation to the master table.
2920 :     $masterRelationTable{$relationshipName} = $thisRelation;
2921 :     }
2922 :     # Now store the master relation table in the metadata structure.
2923 :     $metadata->{RelationTable} = \%masterRelationTable;
2924 :     # Our final task is to create the join table. The join table is a hash that describes all
2925 :     # the join clauses for traveling through the relationships. The join clause is an equality
2926 :     # condition that can be put into a WHERE clause in order to join two objects. Two relationships
2927 :     # can be joined if they share an entity in common; and an entity can be joined to a relationship
2928 :     # if the entity is at either end of the relationship.
2929 :     my %joinTable = ();
2930 :     # Loop through the entities.
2931 :     for my $entityName (keys %{$entityList}) {
2932 :     # Build three lists of the relationships connected to this entity. One will be
2933 :     # for relationships from the entity, one for relationships to the entity, and
2934 :     # one for recursive relationships.
2935 :     my @fromList = ();
2936 :     my @toList = ();
2937 :     my @bothList = ();
2938 : parrello 1.21 Trace("Join table build for $entityName.") if T(metadata => 4);
2939 : parrello 1.10 for my $relationshipName (keys %{$relationshipList}) {
2940 :     my $relationship = $relationshipList->{$relationshipName};
2941 :     # Determine if this relationship has our entity in one of its link fields.
2942 :     my $fromEntity = $relationship->{from};
2943 :     my $toEntity = $relationship->{to};
2944 : parrello 1.41 Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(Joins => 4);
2945 : parrello 1.10 if ($fromEntity eq $entityName) {
2946 :     if ($toEntity eq $entityName) {
2947 :     # Here the relationship is recursive.
2948 :     push @bothList, $relationshipName;
2949 : parrello 1.21 Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
2950 : parrello 1.10 } else {
2951 :     # Here the relationship comes from the entity.
2952 :     push @fromList, $relationshipName;
2953 : parrello 1.21 Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
2954 : parrello 1.10 }
2955 :     } elsif ($toEntity eq $entityName) {
2956 :     # Here the relationship goes to the entity.
2957 :     push @toList, $relationshipName;
2958 : parrello 1.21 Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
2959 : parrello 1.10 }
2960 :     }
2961 :     # Create the nonrecursive joins. Note that we build two hashes for running
2962 :     # through the nonrecursive relationships since we'll have an outer loop
2963 :     # and an inner loop, and we can't do two "each" iterations on the same
2964 :     # hash table at the same time.
2965 :     my %directRelationships = ( from => \@fromList, to => \@toList );
2966 :     my %otherRelationships = ( from => \@fromList, to => \@toList );
2967 :     for my $linkType (keys %directRelationships) {
2968 :     my $relationships = $directRelationships{$linkType};
2969 :     # Loop through all the relationships.
2970 :     for my $relationshipName (@{$relationships}) {
2971 :     # Create joins between the entity and this relationship.
2972 :     my $linkField = "$relationshipName.${linkType}_link";
2973 :     my $joinClause = "$entityName.id = $linkField";
2974 : parrello 1.21 Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4);
2975 : parrello 1.10 $joinTable{"$entityName/$relationshipName"} = $joinClause;
2976 :     $joinTable{"$relationshipName/$entityName"} = $joinClause;
2977 :     # Create joins between this relationship and the other relationships.
2978 :     for my $otherType (keys %otherRelationships) {
2979 :     my $otherships = $otherRelationships{$otherType};
2980 :     for my $otherName (@{$otherships}) {
2981 :     # Get the key for this join.
2982 :     my $joinKey = "$otherName/$relationshipName";
2983 :     # Check for a duplicate or a self-join.
2984 :     if (exists $joinTable{$joinKey}) {
2985 :     # Here we have a duplicate, which means that the join
2986 :     # path is ambiguous. We delete the join from the join
2987 :     # table to prevent it from being used.
2988 :     delete $joinTable{$joinKey};
2989 :     Trace("Deleting ambiguous join $joinKey.") if T(4);
2990 :     } elsif ($otherName ne $relationshipName) {
2991 :     # Here we have a valid join. Note that joins between a
2992 :     # relationship and itself are prohibited.
2993 :     my $relJoinClause = "$otherName.${otherType}_link = $linkField";
2994 :     $joinTable{$joinKey} = $relJoinClause;
2995 : parrello 1.21 Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
2996 : parrello 1.10 }
2997 :     }
2998 :     }
2999 :     # Create joins between this relationship and the recursive relationships.
3000 :     # We don't need to check for ambiguous joins here, because a recursive
3001 :     # relationship can only be ambiguous with another recursive relationship,
3002 :     # and the incoming relationship from the outer loop is never recursive.
3003 :     for my $otherName (@bothList) {
3004 : parrello 1.21 Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4);
3005 : parrello 1.10 # Join from the left.
3006 :     $joinTable{"$relationshipName/$otherName"} =
3007 :     "$linkField = $otherName.from_link";
3008 :     # Join from the right.
3009 :     $joinTable{"$otherName/$relationshipName"} =
3010 :     "$otherName.to_link = $linkField";
3011 :     }
3012 :     }
3013 :     }
3014 :     # Create entity joins for the recursive relationships. Unlike the non-recursive
3015 :     # joins, the direction makes a difference with the recursive joins. This can give
3016 :     # rise to situations where we can't create the path we want; however, it is always
3017 :     # possible to get the same effect using multiple queries.
3018 :     for my $relationshipName (@bothList) {
3019 : parrello 1.21 Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
3020 : parrello 1.10 # Join to the entity from each direction.
3021 :     $joinTable{"$entityName/$relationshipName"} =
3022 :     "$entityName.id = $relationshipName.from_link";
3023 :     $joinTable{"$relationshipName/$entityName"} =
3024 :     "$relationshipName.to_link = $entityName.id";
3025 :     }
3026 :     }
3027 :     # Add the join table to the structure.
3028 :     $metadata->{Joins} = \%joinTable;
3029 :     # Return the slurped and fixed-up structure.
3030 :     return $metadata;
3031 : parrello 1.1 }
3032 :    
3033 : parrello 1.42 =head3 SortNeeded
3034 :    
3035 :     C<< my $flag = $erdb->SortNeeded($relationName); >>
3036 :    
3037 :     Return TRUE if the specified relation should be sorted during loading to remove duplicate keys,
3038 :     else FALSE.
3039 :    
3040 :     =over 4
3041 :    
3042 :     =item relationName
3043 :    
3044 :     Name of the relation to be examined.
3045 :    
3046 :     =item RETURN
3047 :    
3048 :     Returns TRUE if the relation needs a sort, else FALSE.
3049 :    
3050 :     =back
3051 :    
3052 :     =cut
3053 :     #: Return Type $;
3054 :     sub SortNeeded {
3055 :     # Get the parameters.
3056 :     my ($self, $relationName) = @_;
3057 :     # Declare the return variable.
3058 :     my $retVal = 0;
3059 :     # Find out if the relation is a primary entity relation.
3060 : parrello 1.43 my $entityTable = $self->{_metaData}->{Entities};
3061 : parrello 1.42 if (exists $entityTable->{$relationName}) {
3062 :     my $keyType = $entityTable->{$relationName}->{keyType};
3063 : parrello 1.43 Trace("Relation $relationName found in entity table with key type $keyType.") if T(3);
3064 : parrello 1.42 # If the key is not a hash string, we must do the sort.
3065 :     if ($keyType ne 'hash-string') {
3066 :     $retVal = 1;
3067 :     }
3068 :     }
3069 :     # Return the result.
3070 :     return $retVal;
3071 :     }
3072 :    
3073 : parrello 1.1 =head3 CreateRelationshipIndex
3074 :    
3075 :     Create an index for a relationship's relation.
3076 :    
3077 :     This is a static method.
3078 :    
3079 :     =over 4
3080 :    
3081 :     =item indexKey
3082 :    
3083 :     Type of index: either C<"From"> or C<"To">.
3084 :    
3085 :     =item relationshipName
3086 :    
3087 :     Name of the relationship.
3088 :    
3089 :     =item relationshipStructure
3090 :    
3091 :     Structure describing the relationship that the index will sort.
3092 :    
3093 :     =back
3094 :    
3095 :     =cut
3096 :    
3097 :     sub _CreateRelationshipIndex {
3098 : parrello 1.10 # Get the parameters.
3099 :     my ($indexKey, $relationshipName, $relationshipStructure) = @_;
3100 :     # Get the target relation.
3101 :     my $relationStructure = $relationshipStructure->{Relations}->{$relationshipName};
3102 :     # Create a descriptor for the link field that goes at the beginning of this index.
3103 :     my $firstField = { name => lcfirst $indexKey . '-link', order => 'ascending' };
3104 :     # Get the target index descriptor.
3105 :     my $newIndex = $relationshipStructure->{$indexKey . "Index"};
3106 :     # Add the first field to the index's field list. Due to the craziness of PERL, if the
3107 :     # index descriptor does not exist, it will be created automatically so we can add
3108 :     # the field to it.
3109 :     unshift @{$newIndex->{IndexFields}}, $firstField;
3110 : parrello 1.12 # If this is a one-to-many relationship, the "To" index is unique.
3111 :     if ($relationshipStructure->{arity} eq "1M" && $indexKey eq "To") {
3112 :     $newIndex->{Unique} = 'true';
3113 :     }
3114 : parrello 1.10 # Add the index to the relation.
3115 :     _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
3116 : parrello 1.1 }
3117 :    
3118 :     =head3 AddIndex
3119 :    
3120 :     Add an index to a relation structure.
3121 :    
3122 :     This is a static method.
3123 :    
3124 :     =over 4
3125 :    
3126 :     =item indexName
3127 :    
3128 :     Name to give to the new index.
3129 :    
3130 :     =item relationStructure
3131 :    
3132 :     Relation structure to which the new index should be added.
3133 :    
3134 :     =item newIndex
3135 :    
3136 :     New index to add.
3137 :    
3138 :     =back
3139 :    
3140 :     =cut
3141 :    
3142 :     sub _AddIndex {
3143 : parrello 1.10 # Get the parameters.
3144 :     my ($indexName, $relationStructure, $newIndex) = @_;
3145 :     # We want to re-do the index's field list. Instead of an object for each field,
3146 :     # we want a string consisting of the field name optionally followed by the token DESC.
3147 :     my @fieldList = ( );
3148 :     for my $field (@{$newIndex->{IndexFields}}) {
3149 :     # Create a string containing the field name.
3150 :     my $fieldString = $field->{name};
3151 :     # Add the ordering token if needed.
3152 :     if ($field->{order} eq "descending") {
3153 :     $fieldString .= " DESC";
3154 :     }
3155 :     # Push the result onto the field list.
3156 :     push @fieldList, $fieldString;
3157 :     }
3158 :     # Store the field list just created as the new index field list.
3159 :     $newIndex->{IndexFields} = \@fieldList;
3160 :     # Add the index to the relation's index list.
3161 :     $relationStructure->{Indexes}->{$indexName} = $newIndex;
3162 : parrello 1.1 }
3163 :    
3164 :     =head3 FixupFields
3165 :    
3166 :     This method fixes the field list for an entity or relationship. It will add the caller-specified
3167 :     relation name to fields that do not have a name and set the C<PrettySort> value as specified.
3168 :    
3169 :     This is a static method.
3170 :    
3171 :     =over 4
3172 :    
3173 :     =item structure
3174 :    
3175 :     Entity or relationship structure to be fixed up.
3176 :    
3177 :     =item defaultRelationName
3178 :    
3179 :     Default relation name to be added to the fields.
3180 :    
3181 :     =item prettySortValue
3182 :    
3183 :     C<PrettySort> value for the relation's normal fields.
3184 :    
3185 :     =item textPrettySortValue
3186 :    
3187 :     C<PrettySort> value for the relation's text fields. This value can be set to one greater than the
3188 :     normal pretty sort value so that text fields go at the end of each relation.
3189 :    
3190 :     =back
3191 :    
3192 :     =cut
3193 :    
3194 :     sub _FixupFields {
3195 : parrello 1.10 # Get the parameters.
3196 :     my ($structure, $defaultRelationName, $prettySortValue, $textPrettySortValue) = @_;
3197 :     # Insure the structure has a field list.
3198 :     if (!exists $structure->{Fields}) {
3199 :     # Here it doesn't, so we create a new one.
3200 :     $structure->{Fields} = { };
3201 :     } else {
3202 :     # Here we have a field list. Loop through its fields.
3203 :     my $fieldStructures = $structure->{Fields};
3204 :     for my $fieldName (keys %{$fieldStructures}) {
3205 : parrello 1.8 Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
3206 : parrello 1.10 my $fieldData = $fieldStructures->{$fieldName};
3207 :     # Get the field type.
3208 :     my $type = $fieldData->{type};
3209 :     # Plug in a relation name if it is needed.
3210 :     Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
3211 :     # Plug in a data generator if we need one.
3212 :     if (!exists $fieldData->{DataGen}) {
3213 :     # The data generator will use the default for the field's type.
3214 :     $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };
3215 :     }
3216 :     # Plug in the defaults for the optional data generation parameters.
3217 :     Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });
3218 :     # Add the PrettySortValue.
3219 :     $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
3220 :     }
3221 :     }
3222 : parrello 1.1 }
3223 :    
3224 :     =head3 FixName
3225 :    
3226 :     Fix the incoming field name so that it is a legal SQL column name.
3227 :    
3228 :     This is a static method.
3229 :    
3230 :     =over 4
3231 :    
3232 :     =item fieldName
3233 :    
3234 :     Field name to fix.
3235 :    
3236 :     =item RETURN
3237 :    
3238 :     Returns the fixed-up field name.
3239 :    
3240 :     =back
3241 :    
3242 :     =cut
3243 :    
3244 :     sub _FixName {
3245 : parrello 1.10 # Get the parameter.
3246 :     my ($fieldName) = @_;
3247 :     # Replace its minus signs with underscores.
3248 :     $fieldName =~ s/-/_/g;
3249 :     # Return the result.
3250 :     return $fieldName;
3251 : parrello 1.1 }
3252 :    
3253 :     =head3 FixNames
3254 :    
3255 :     Fix all the field names in a list.
3256 :    
3257 :     This is a static method.
3258 :    
3259 :     =over 4
3260 :    
3261 :     =item field1, field2, field3, ... fieldn
3262 :    
3263 :     List of field names to fix.
3264 :    
3265 :     =item RETURN
3266 :    
3267 :     Returns a list of fixed-up versions of the incoming field names.
3268 :    
3269 :     =back
3270 :    
3271 :     =cut
3272 :    
3273 :     sub _FixNames {
3274 : parrello 1.10 # Create the result list.
3275 :     my @result = ( );
3276 :     # Loop through the incoming parameters.
3277 :     for my $field (@_) {
3278 :     push @result, _FixName($field);
3279 :     }
3280 :     # Return the result.
3281 :     return @result;
3282 : parrello 1.1 }
3283 :    
3284 :     =head3 AddField
3285 :    
3286 :     Add a field to a field list.
3287 :    
3288 :     This is a static method.
3289 :    
3290 :     =over 4
3291 :    
3292 :     =item structure
3293 :    
3294 :     Structure (usually an entity or relationship) that is to contain the field.
3295 :    
3296 :     =item fieldName
3297 :    
3298 :     Name of the new field.
3299 :    
3300 :     =item fieldData
3301 :    
3302 :     Structure containing the data to put in the field.
3303 :    
3304 :     =back
3305 :    
3306 :     =cut
3307 :    
3308 :     sub _AddField {
3309 : parrello 1.10 # Get the parameters.
3310 :     my ($structure, $fieldName, $fieldData) = @_;
3311 :     # Create the field structure by copying the incoming data.
3312 :     my $fieldStructure = {%{$fieldData}};
3313 :     # Get a reference to the field list itself.
3314 :     my $fieldList = $structure->{Fields};
3315 :     # Add the field to the field list.
3316 :     $fieldList->{$fieldName} = $fieldStructure;
3317 : parrello 1.1 }
3318 :    
3319 :     =head3 ReOrderRelationTable
3320 :    
3321 :     This method will take a relation table and re-sort it according to the implicit ordering of the
3322 :     C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.
3323 :     This requires creating a new hash that contains the field name in the C<name> property but doesn't
3324 :     have the C<PrettySort> property, and then inserting that new hash into the field list.
3325 :    
3326 :     This is a static method.
3327 :    
3328 :     =over 4
3329 :    
3330 :     =item relationTable
3331 :    
3332 :     Relation hash to be reformatted into a list.
3333 :    
3334 :     =item RETURN
3335 :    
3336 :     A list of field hashes.
3337 :    
3338 :     =back
3339 :    
3340 :     =cut
3341 :    
3342 :     sub _ReOrderRelationTable {
3343 : parrello 1.10 # Get the parameters.
3344 :     my ($relationTable) = @_;
3345 :     # Create the return list.
3346 :     my @resultList;
3347 :     # Rather than copy all the fields in a single pass, we make multiple passes and only copy
3348 :     # fields whose PrettySort value matches the current pass number. This process continues
3349 :     # until we process all the fields in the relation.
3350 :     my $fieldsLeft = (values %{$relationTable});
3351 :     for (my $sortPass = 1; $fieldsLeft > 0; $sortPass++) {
3352 :     # Loop through the fields. Note that we lexically sort the fields. This makes field name
3353 :     # secondary to pretty-sort number in the final ordering.
3354 :     for my $fieldName (sort keys %{$relationTable}) {
3355 :     # Get this field's data.
3356 :     my $fieldData = $relationTable->{$fieldName};
3357 :     # Verify the sort pass.
3358 :     if ($fieldData->{PrettySort} == $sortPass) {
3359 :     # Here we're in the correct pass. Denote we've found a field.
3360 :     $fieldsLeft--;
3361 :     # The next step is to create the field structure. This done by copying all
3362 :     # of the field elements except PrettySort and adding the name.
3363 :     my %thisField;
3364 :     for my $property (keys %{$fieldData}) {
3365 :     if ($property ne 'PrettySort') {
3366 :     $thisField{$property} = $fieldData->{$property};
3367 :     }
3368 :     }
3369 :     $thisField{name} = $fieldName;
3370 :     # Now we add this field to the end of the result list.
3371 :     push @resultList, \%thisField;
3372 :     }
3373 :     }
3374 :     }
3375 :     # Return a reference to the result list.
3376 :     return \@resultList;
3377 : parrello 1.1
3378 :     }
3379 :    
3380 :     =head3 IsPrimary
3381 :    
3382 :     Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary
3383 :     if it has the same name as an entity or relationship.
3384 :    
3385 :     This is an instance method.
3386 :    
3387 :     =over 4
3388 :    
3389 :     =item relationName
3390 :    
3391 :     Name of the relevant relation.
3392 :    
3393 :     =item RETURN
3394 :    
3395 :     Returns TRUE for a primary relation, else FALSE.
3396 :    
3397 :     =back
3398 :    
3399 :     =cut
3400 :    
3401 :     sub _IsPrimary {
3402 : parrello 1.10 # Get the parameters.
3403 :     my ($self, $relationName) = @_;
3404 :     # Check for the relation in the entity table.
3405 :     my $entityTable = $self->{_metaData}->{Entities};
3406 :     my $retVal = exists $entityTable->{$relationName};
3407 :     if (! $retVal) {
3408 :     # Check for it in the relationship table.
3409 :     my $relationshipTable = $self->{_metaData}->{Relationships};
3410 :     $retVal = exists $relationshipTable->{$relationName};
3411 :     }
3412 :     # Return the determination indicator.
3413 :     return $retVal;
3414 : parrello 1.1 }
3415 :    
3416 :     =head3 FindRelation
3417 :    
3418 :     Return the descriptor for the specified relation.
3419 :    
3420 :     This is an instance method.
3421 :    
3422 :     =over 4
3423 :    
3424 :     =item relationName
3425 :    
3426 :     Name of the relation whose descriptor is to be returned.
3427 :    
3428 :     =item RETURN
3429 :    
3430 :     Returns the object that describes the relation's indexes and fields.
3431 :    
3432 :     =back
3433 :    
3434 :     =cut
3435 :     sub _FindRelation {
3436 : parrello 1.10 # Get the parameters.
3437 :     my ($self, $relationName) = @_;
3438 :     # Get the relation's structure from the master relation table in the metadata structure.
3439 :     my $metaData = $self->{_metaData};
3440 :     my $retVal = $metaData->{RelationTable}->{$relationName};
3441 :     # Return it to the caller.
3442 :     return $retVal;
3443 : parrello 1.1 }
3444 :    
3445 :     =head2 HTML Documentation Utility Methods
3446 :    
3447 :     =head3 ComputeRelationshipSentence
3448 :    
3449 :     The relationship sentence consists of the relationship name between the names of the
3450 :     two related entities and an arity indicator.
3451 :    
3452 :     This is a static method.
3453 :    
3454 :     =over 4
3455 :    
3456 :     =item relationshipName
3457 :    
3458 :     Name of the relationship.
3459 :    
3460 :     =item relationshipStructure
3461 :    
3462 :     Relationship structure containing the relationship's description and properties.
3463 :    
3464 :     =item RETURN
3465 :    
3466 :     Returns a string containing the entity names on either side of the relationship name and an
3467 :     indicator of the arity.
3468 :    
3469 :     =back
3470 :    
3471 :     =cut
3472 :    
3473 :     sub _ComputeRelationshipSentence {
3474 : parrello 1.10 # Get the parameters.
3475 :     my ($relationshipName, $relationshipStructure) = @_;
3476 :     # Format the relationship sentence.
3477 :     my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";
3478 :     # Compute the arity.
3479 :     my $arityCode = $relationshipStructure->{arity};
3480 :     my $arity = $ArityTable{$arityCode};
3481 :     $result .= " ($arity)";
3482 :     return $result;
3483 : parrello 1.1 }
3484 :    
3485 :     =head3 ComputeRelationshipHeading
3486 :    
3487 :     The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
3488 :     names hyperlinked to the appropriate entity sections of the document.
3489 :    
3490 :     This is a static method.
3491 :    
3492 :     =over 4
3493 :    
3494 :     =item relationshipName
3495 :    
3496 :     Name of the relationship.
3497 :    
3498 :     =item relationshipStructure
3499 :    
3500 :     Relationship structure containing the relationship's description and properties.
3501 :    
3502 :     =item RETURN
3503 :    
3504 :     Returns a string containing the entity names on either side of the relationship name with the entity
3505 :     names hyperlinked.
3506 :    
3507 :     =back
3508 :    
3509 :     =cut
3510 :    
3511 :     sub _ComputeRelationshipHeading {
3512 : parrello 1.10 # Get the parameters.
3513 :     my ($relationshipName, $relationshipStructure) = @_;
3514 :     # Get the FROM and TO entity names.
3515 :     my $fromEntity = $relationshipStructure->{from};
3516 :     my $toEntity = $relationshipStructure->{to};
3517 :     # Format a relationship sentence with hyperlinks in it.
3518 :     my $result = "<a href=\"#$fromEntity\">$fromEntity</a> $relationshipName <a href=\"#$toEntity\">$toEntity</a>";
3519 :     return $result;
3520 : parrello 1.1 }
3521 :    
3522 :     =head3 ShowRelationTable
3523 :    
3524 :     Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
3525 :     table with three columns-- the field name, the field type, and the field description.
3526 :    
3527 :     This is a static method.
3528 :    
3529 :     =over 4
3530 :    
3531 :     =item relationName
3532 :    
3533 :     Name of the relation being formatted.
3534 :    
3535 :     =item relationData
3536 :    
3537 :     Hash containing the relation's fields and indexes.
3538 :    
3539 :     =item RETURN
3540 :    
3541 :     Returns an HTML string that can be used to display the relation name and all of its fields.
3542 :    
3543 :     =back
3544 :    
3545 :     =cut
3546 :    
3547 :     sub _ShowRelationTable {
3548 : parrello 1.10 # Get the parameters.
3549 :     my ($relationName, $relationData) = @_;
3550 :     # Start the relation's field table.
3551 :     my $htmlString = _OpenFieldTable($relationName);
3552 :     # Loop through the fields.
3553 :     for my $field (@{$relationData->{Fields}}) {
3554 :     $htmlString .= _ShowField($field);
3555 :     }
3556 :     # Close this relation's field table.
3557 :     $htmlString .= &_CloseTable;
3558 :     # Now we show the relation's indexes.
3559 :     $htmlString .= "<ul>\n";
3560 :     my $indexTable = $relationData->{Indexes};
3561 :     for my $indexName (sort keys %{$indexTable}) {
3562 :     my $indexData = $indexTable->{$indexName};
3563 :     # Determine whether or not the index is unique.
3564 :     my $fullName = $indexName;
3565 :     if (exists $indexData->{Unique} && $indexData->{Unique} eq "true") {
3566 :     $fullName .= " (unique)";
3567 :     }
3568 :     # Start an HTML list item for this index.
3569 :     $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
3570 :     # Add any note text.
3571 :     if (my $note = $indexData->{Notes}) {
3572 :     $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";
3573 :     }
3574 :     # Add the fiield list.
3575 :     $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
3576 :     # Close this entry.
3577 :     $htmlString .= "</ul></li>\n";
3578 :     }
3579 :     # Close off the index list.
3580 :     $htmlString .= "</ul>\n";
3581 : parrello 1.1 }
3582 :    
3583 :     =head3 OpenFieldTable
3584 :    
3585 :     This method creates the header string for the field table generated by L</ShowMetaData>.
3586 :    
3587 :     This is a static method.
3588 :    
3589 :     =over 4
3590 :    
3591 :     =item tablename
3592 :    
3593 :     Name of the table whose fields will be displayed.
3594 :    
3595 :     =item RETURN
3596 :    
3597 :     Returns a string containing the HTML for a field table's header.
3598 :    
3599 :     =back
3600 :    
3601 :     =cut
3602 :    
3603 :     sub _OpenFieldTable {
3604 : parrello 1.10 my ($tablename) = @_;
3605 :     return _OpenTable($tablename, 'Field', 'Type', 'Description');
3606 : parrello 1.1 }
3607 :    
3608 :     =head3 OpenTable
3609 :    
3610 :     This method creates the header string for an HTML table.
3611 :    
3612 :     This is a static method.
3613 :    
3614 :     =over 4
3615 :    
3616 :     =item tablename
3617 :    
3618 :     Title of the table.
3619 :    
3620 :     =item colName1, colName2, ..., colNameN
3621 :    
3622 :     List of column names.
3623 :    
3624 :     =item RETURN
3625 :    
3626 :     Returns a string containing the HTML for the desired table's header.
3627 :    
3628 :     =back
3629 :    
3630 :     =cut
3631 :    
3632 :     sub _OpenTable {
3633 : parrello 1.10 # Get the parameters.
3634 :     my ($tablename, @colNames) = @_;
3635 :     # Compute the number of columns.
3636 :     my $colCount = @colNames;
3637 :     # Generate the title row.
3638 :     my $htmlString = "<p><table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";
3639 :     # Loop through the columns, adding the column header rows.
3640 :     $htmlString .= "<tr>";
3641 :     for my $colName (@colNames) {
3642 :     $htmlString .= "<th>$colName</th>";
3643 :     }
3644 :     $htmlString .= "</tr>\n";
3645 :     return $htmlString;
3646 : parrello 1.1 }
3647 :    
3648 :     =head3 CloseTable
3649 :    
3650 :     This method returns the HTML for closing a table.
3651 :    
3652 :     This is a static method.
3653 :    
3654 :     =cut
3655 :    
3656 :     sub _CloseTable {
3657 : parrello 1.10 return "</table></p>\n";
3658 : parrello 1.1 }
3659 :    
3660 :     =head3 ShowField
3661 :    
3662 :     This method returns the HTML for displaying a row of field information in a field table.
3663 :    
3664 :     This is a static method.
3665 :    
3666 :     =over 4
3667 :    
3668 :     =item fieldData
3669 :    
3670 :     Table of data about the field.
3671 :    
3672 :     =item RETURN
3673 :    
3674 :     Returns an HTML string for a table row that shows the field's name, type, and description.
3675 :    
3676 :     =back
3677 :    
3678 :     =cut
3679 :    
3680 :     sub _ShowField {
3681 : parrello 1.10 # Get the parameters.
3682 :     my ($fieldData) = @_;
3683 :     # Create the HTML string.
3684 :     my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";
3685 :     # If we have content, add it as a third column.
3686 :     if (exists $fieldData->{Notes}) {
3687 :     $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";
3688 :     }
3689 :     # Close off the row.
3690 :     $htmlString .= "</tr>\n";
3691 :     # Return the result.
3692 :     return $htmlString;
3693 : parrello 1.1 }
3694 :    
3695 :     =head3 HTMLNote
3696 :    
3697 :     Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3698 :     supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3699 :     Except for C<[p]>, all the codes are closed by slash-codes. So, for
3700 :     example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3701 :    
3702 :     This is a static method.
3703 :    
3704 :     =over 4
3705 :    
3706 :     =item dataString
3707 :    
3708 :     String to convert to HTML.
3709 :    
3710 :     =item RETURN
3711 :    
3712 :     An HTML string derived from the input string.
3713 :    
3714 :     =back
3715 :    
3716 :     =cut
3717 :    
3718 :     sub _HTMLNote {
3719 : parrello 1.10 # Get the parameter.
3720 :     my ($dataString) = @_;
3721 :     # Substitute the codes.
3722 :     $dataString =~ s!\[(/?[bi])\]!<$1>!g;
3723 :     $dataString =~ s!\[p\]!</p><p>!g;
3724 :     # Return the result.
3725 :     return $dataString;
3726 : parrello 1.1 }
3727 :    
3728 :     =head2 Data Generation Utilities
3729 :    
3730 :     =head3 IntGen
3731 :    
3732 :     C<< my $integer = IntGen($min, $max); >>
3733 :    
3734 :     Returns a random number between the specified minimum and maximum (inclusive).
3735 :    
3736 :     =over 4
3737 :    
3738 :     =item min
3739 :    
3740 :     Minimum permissible return value.
3741 :    
3742 :     =item max
3743 :    
3744 :     Maximum permissible return value.
3745 :    
3746 :     =item RETURN
3747 :    
3748 :     Returns a value no lower than the minimum and no greater than the maximum.
3749 :    
3750 :     =back
3751 :    
3752 :     =cut
3753 :    
3754 :     sub IntGen {
3755 : parrello 1.10 # Get the parameters.
3756 :     my ($min, $max) = @_;
3757 :     # Determine the range of possible values. Note we put some space well above the
3758 :     # maximum value to give it a fighting chance of apppearing in the list.
3759 :     my $span = $max + 0.99 - $min;
3760 :     # Create an integer in the range.
3761 :     my $retVal = $min + int(rand($span));
3762 :     # Return the result.
3763 :     return $retVal;
3764 : parrello 1.1 }
3765 :    
3766 :     =head3 RandChar
3767 :    
3768 :     C<< my $char = RandChar($sourceString); >>
3769 :    
3770 :     Select a random character from a string.
3771 :    
3772 :     =over 4
3773 :    
3774 :     =item sourceString
3775 :    
3776 :     String from which the random character should be selected.
3777 :    
3778 :     =item RETURN
3779 :    
3780 :     Returns a single character from the incoming string.
3781 :    
3782 :     =back
3783 :    
3784 :     =cut
3785 :    
3786 :     sub RandChar {
3787 : parrello 1.10 # Get the parameter.
3788 :     my ($sourceString) = @_;
3789 :     # Select a random character.
3790 :     my $retVal = IntGen(0, (length $sourceString) - 1);
3791 :     # Return it.
3792 :     return substr($sourceString, $retVal, 1);
3793 : parrello 1.1 }
3794 :    
3795 :     =head3 RandChars
3796 :    
3797 :     C<< my $string = RandChars($sourceString, $length); >>
3798 :    
3799 :     Create a string from characters taken from a source string.
3800 :    
3801 :     =over 4
3802 :    
3803 :     =item sourceString
3804 :    
3805 :     String from which the random characters should be selected.
3806 :    
3807 :     =item length
3808 :    
3809 :     Number of characters to put in the output string.
3810 :    
3811 :     =item RETURN
3812 :    
3813 :     Returns a string of the specified length consisting of characters taken from the
3814 :     source string.
3815 :    
3816 :     =back
3817 :    
3818 :     =cut
3819 :    
3820 :     sub RandChars {
3821 : parrello 1.10 # Get the parameters.
3822 :     my ($sourceString, $length) = @_;
3823 :     # Call RandChar repeatedly to generate the string.
3824 :     my $retVal = "";
3825 :     for (my $i = 0; $i < $length; $i++) {
3826 :     $retVal .= RandChar($sourceString);
3827 :     }
3828 :     # Return the result.
3829 :     return $retVal;
3830 : parrello 1.1 }
3831 :    
3832 :     =head3 RandParam
3833 :    
3834 :     C<< my $value = RandParam($parm1, $parm2, ... $parmN); >>
3835 :    
3836 :     Return a randomly-selected value from the parameter list.
3837 :    
3838 :     =over 4
3839 :    
3840 :     =item parm1, parm2, ... parmN
3841 :    
3842 :     List of values of which one will be selected.
3843 :    
3844 :     =item RETURN
3845 :    
3846 :     Returns a randomly-chosen value from the specified list.
3847 :    
3848 :     =back
3849 :    
3850 :     =cut
3851 :    
3852 :     sub RandParam {
3853 : parrello 1.10 # Get the parameter.
3854 :     my @parms = @_;
3855 :     # Choose a random parameter from the list.
3856 :     my $chosenIndex = IntGen(0, $#parms);
3857 :     return $parms[$chosenIndex];
3858 : parrello 1.1 }
3859 :    
3860 :     =head3 StringGen
3861 :    
3862 :     C<< my $string = StringGen($pattern1, $pattern2, ... $patternN); >>
3863 :    
3864 :     Returns a random string derived from a randomly-chosen format pattern. The pattern
3865 :     can either be a number (indicating the number of characters desired, or the letter
3866 :     C<P> followed by a picture. The picture should contain C<A> when a letter is desired,
3867 :     C<9> when a digit is desired, C<V> when a vowel is desired, C<K> when a consonant is
3868 :     desired, and C<X> when a letter or a digit is desired. Any other character will be
3869 :     translated as a literal.
3870 :    
3871 :     =over 4
3872 :    
3873 :     =item pattern1, pattern2, ... patternN
3874 :    
3875 :     List of patterns to be used to generate string values.
3876 :    
3877 :     =item RETURN
3878 :    
3879 :     A single string generated from a pattern.
3880 :    
3881 :     =back
3882 :    
3883 :     =cut
3884 :    
3885 :     sub StringGen {
3886 : parrello 1.10 # Get the parameters.
3887 :     my @patterns = @_;
3888 :     # Choose the appropriate pattern.
3889 :     my $chosenPattern = RandParam(@patterns);
3890 :     # Declare the return variable.
3891 :     my $retVal = "";
3892 :     # Determine whether this is a count or a picture pattern.
3893 :     if ($chosenPattern =~ m/^\d+/) {
3894 :     # Here we have a count. Get the string of source characters.
3895 :     my $letterString = $PictureTable{'X'};
3896 :     my $stringLen = length $letterString;
3897 :     # Save the number of characters we have to generate.
3898 :     my $charsLeft = $chosenPattern;
3899 :     # Loop until the return variable is full.
3900 :     while ($charsLeft > 0) {
3901 :     # Generate a random position in the soruce string.
3902 :     my $stringIndex = IntGen(0, $stringLen - 1);
3903 :     # Compute the number of characters to pull out of the source string.
3904 :     my $chunkSize = $stringLen - $stringIndex;
3905 :     if ($chunkSize > $charsLeft) { $chunkSize = $charsLeft; }
3906 :     # Stuff this chunk into the return value.
3907 :     $retVal .= substr($letterString, $stringIndex, $chunkSize);
3908 :     # Record the data moved.
3909 :     $charsLeft -= $chunkSize;
3910 :     }
3911 :     } elsif ($chosenPattern =~ m/^P/) {
3912 :     # Here we have a picture string. We will move through the picture one
3913 :     # character at a time generating data.
3914 :     for (my $i = 1; $i < length $chosenPattern; $i++) {
3915 :     # Get this picture character.
3916 :     my $chr = substr($chosenPattern, $i, 1);
3917 :     # Check to see if the picture char is one we recognize.
3918 :     if (exists $PictureTable{$chr}) {
3919 :     # Choose a random character from the available values for this
3920 :     # picture character.
3921 :     $retVal .= RandChar($PictureTable{$chr});
3922 :     } else {
3923 :     # Copy in the picture character as a literal.
3924 :     $retVal .= $chr;
3925 :     }
3926 :     }
3927 :     } else {
3928 :     # Here we have neither a picture string or a letter count, so we treat
3929 :     # the string as a literal.
3930 :     $retVal = $chosenPattern;
3931 :     }
3932 :     # Return the string formed.
3933 :     return $retVal;
3934 : parrello 1.1 }
3935 :    
3936 :     =head3 DateGen
3937 :    
3938 :     C<< my $date = DateGen($startDayOffset, $endDayOffset, $minutes); >>
3939 :    
3940 :     Return a numeric timestamp within the specified range of days with the specified minute
3941 :     value. The range of days is specified relevant to the current day. Thus, the call
3942 :    
3943 :     C<< my $date = DateGen(-1, 5, 720); >>
3944 :    
3945 :     will return a timestamp at noon (72 minutes past midnight) sometime during the week that
3946 :     began on the preceding day. If you want a random minute of the day, simply combine with
3947 :     a call to L</IntGen>, as follows.
3948 :    
3949 :     C<< my $date = DateGen(-1, 5, IntGen(0, 1439)); >>
3950 :    
3951 :     =over 4
3952 :    
3953 :     =item startDayOffset
3954 :    
3955 :     The earliest day that can be returned, relative to the current day.
3956 :    
3957 :     =item endDayOffset
3958 :    
3959 :     The latest day that can be returned, related to the current day.
3960 :    
3961 :     =item minutes
3962 :    
3963 :     Number of minutes into the selected day that should be used.
3964 :    
3965 :     =back
3966 :    
3967 :     =cut
3968 :    
3969 :     sub DateGen {
3970 : parrello 1.10 # Get the parameters.
3971 :     my ($startDayOffset, $endDayOffset, $minutes) = @_;
3972 :     # Get midnight of the current day.
3973 :     my $now = time();
3974 :     my ($sec, $min, $hour) = localtime($now);
3975 :     my $today = $now - (($hour * 60 + $min) * 60 + $sec);
3976 :     # Compute the day we want.
3977 :     my $newDay = IntGen($startDayOffset, $endDayOffset) * 86400 + $today;
3978 :     # Add the minutes.
3979 :     my $retVal = $newDay + $minutes * 60;
3980 :     # Return the result.
3981 :     return $retVal;
3982 : parrello 1.1 }
3983 :    
3984 :     =head3 FloatGen
3985 :    
3986 :     C<< my $number = FloatGen($min, $max); >>
3987 :    
3988 :     Return a random floating-point number greater than or equal to the specified minimum and
3989 :     less than the specified maximum.
3990 :    
3991 :     =over 4
3992 :    
3993 :     =item min
3994 :    
3995 :     Minimum permissible value for the number returned.
3996 :    
3997 :     =item max
3998 :    
3999 :     Maximum permissible value for the number returned.
4000 :    
4001 :     =item RETURN
4002 :    
4003 :     Returns a floating-point number anywhere in the specified range.
4004 :    
4005 :     =back
4006 :    
4007 :     =cut
4008 :    
4009 :     sub FloatGen {
4010 : parrello 1.10 # Get the parameters.
4011 :     my ($min, $max) = @_;
4012 :     # Generate the result.
4013 :     my $retVal = rand($max - $min) + $min;
4014 :     return $retVal;
4015 : parrello 1.1 }
4016 :    
4017 :     =head3 ListGen
4018 :    
4019 :     C<< my @list = ListGen($pattern, $count); >>
4020 :    
4021 :     Return a list containing a fixed number of randomly-generated strings.
4022 :    
4023 :     =over 4
4024 :    
4025 :     =item pattern
4026 :    
4027 :     A pattern (in the form expected by L</StringGen>) that should be used to generate the
4028 :     strings in the list.
4029 :    
4030 :     =item count
4031 :    
4032 :     The number of list entries to generate.
4033 :    
4034 :     =item RETURN
4035 :    
4036 :     Returns a list consisting of the specified number of strings.
4037 :    
4038 :     =back
4039 :    
4040 :     =cut
4041 :    
4042 :     sub ListGen {
4043 : parrello 1.10 # Get the parameters.
4044 :     my ($pattern, $count) = @_;
4045 :     # Generate the list.
4046 :     my @retVal = ();
4047 :     for (my $i = 0; $i < $count; $i++) {
4048 :     push @retVal, StringGen($pattern);
4049 :     }
4050 :     # Return it.
4051 :     return @retVal;
4052 : parrello 1.1 }
4053 :    
4054 : overbeek 1.11 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3