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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3