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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3