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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3