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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3