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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3