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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3