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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3