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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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