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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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