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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.40 - (view) (download) (as text)

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3