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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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