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

Annotation of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : parrello 1.1 package ERDB;
2 :    
3 : olson 1.139 #
4 :     # This is a SAS component
5 :     #
6 :    
7 : parrello 1.10 use strict;
8 : parrello 1.111 use base qw(Exporter);
9 :     use vars qw(@EXPORT_OK);
10 :     @EXPORT_OK = qw(encode);
11 : parrello 1.10 use Tracer;
12 :     use Data::Dumper;
13 :     use XML::Simple;
14 : parrello 1.111 use ERDBQuery;
15 : parrello 1.88 use ERDBObject;
16 : parrello 1.10 use Stats;
17 :     use Time::HiRes qw(gettimeofday);
18 : parrello 1.42 use Digest::MD5 qw(md5_base64);
19 : parrello 1.111 use CGI qw(-nosticky);
20 : olson 1.139
21 : parrello 1.120 use ERDBExtras;
22 : parrello 1.126 use FreezeThaw;
23 : parrello 1.1
24 :     =head1 Entity-Relationship Database Package
25 :    
26 :     =head2 Introduction
27 :    
28 : parrello 1.111 The Entity-Relationship Database Package allows the client to create an
29 :     easily-configurable database of Entities connected by Relationships. Each entity
30 :     is represented by one or more relations in an underlying SQL database. Each
31 :     relationship is represented by a single relation that connects two entities.
32 :     Entities and relationships are collectively referred to in the documentation as
33 :     I<objects>.
34 :    
35 :     Although this package is designed for general use, most examples are derived
36 :     from the world of bioinformatics, which is where this technology was first
37 :     deployed.
38 :    
39 :     Each entity has at least one relation, the I<primary relation>, that has the
40 :     same name as the entity. The primary relation contains a field named C<id> that
41 :     contains the unique identifier of each entity instance. An entity may have
42 :     additional relations that contain fields which are optional or can occur more
43 :     than once. For example, the C<Feature> entity has a B<feature-type> attribute
44 :     that occurs exactly once for each feature. This attribute is implemented by a
45 :     C<feature_type> column in the primary relation C<Feature>. In addition, however,
46 :     a feature may have zero or more aliases. These are implemented using a
47 :     C<FeatureAlias> relation that contains two fields-- the feature ID (C<id>) and
48 :     the alias name (C<alias>). The C<Feature> entity also contains an optional
49 :     virulence number. This is implemented as a separate relation C<FeatureVirulence>
50 :     which contains an ID (C<id>) and a virulence number (C<virulence>). If the
51 :     virulence of a feature I<ABC> is known to be 6, there will be one row in the
52 :     C<FeatureVirulence> relation possessing the value I<ABC> as its ID and 6 as its
53 :     virulence number. If the virulence of I<ABC> is not known, there will not be any
54 :     rows for it in C<FeatureVirulence>.
55 :    
56 :     Entities are connected by binary relationships implemented using single
57 :     relations possessing the same name as the relationship itself and that has an
58 :     1-to-many (C<1M>) or many-to-many (C<MM>). Each relationship's relation contains
59 :     a C<from-link> field that contains the ID of the source entity and a C<to-link>
60 :     field that contains the ID of the target entity. The name of the relationship is
61 :     generally a verb phrase with the source entity as the subject and the target
62 :     entity as the object. So, for example, the B<ComesFrom> relationship connects
63 :     the C<Genome> and C<Source> entities, and indicates that a particular source
64 :     organization participated in the mapping of the genome. A source organization
65 :     frequently participates in the mapping of many genomes, and many source
66 :     organizations can cooperate in the mapping of a single genome, so this
67 :     relationship has an arity of many-to-many (C<MM>). The relation that implements
68 :     the C<ComesFrom> relationship is called C<ComesFrom> and contains two fields--
69 :     C<from-link>, which contains a genome ID, and C<to-link>, which contains a
70 :     source ID.
71 :    
72 :     A relationship may itself have attributes. These attributes, known as
73 :     I<intersection data attributes>, are implemented as additional fields in the
74 :     relationship's relation. So, for example, the B<IsMadeUpOf> relationship
75 :     connects the B<Contig> entity to the B<Sequence> entity, and is used to
76 :     determine which sequences make up a contig. The relationship has as an attribute
77 :     the B<start-position>, which indicates where in the contig that the sequence
78 :     begins. This attribute is implemented as the C<start_position> field in the
79 :     C<IsMadeUpOf> relation.
80 :    
81 :     The database itself is described by an XML file. In addition to all the data
82 :     required to define the entities, relationships, and attributes, the schema
83 :     provides space for notes describing the data and what it means and information
84 :     about how to display a diagram of the database. These are used to create web
85 :     pages describing the data.
86 :    
87 :     Special support is provided for text searching. An entity field can be marked as
88 :     I<searchable>, in which case it will be used to generate a text search
89 :     index in which the user searches for words in the field instead of a particular
90 :     field value.
91 :    
92 :     =head2 Loading
93 :    
94 :     Considerable support is provided for loading a database from flat files. The
95 :     flat files are in the standard format expected by the MySQL C<LOAD DATA INFILE>
96 :     command. This command expects each line to represent a database record and
97 :     each record to have all the fields specified, in order, with tab characters
98 :     separating the fields.
99 :    
100 : parrello 1.123 The L<ERDBLoadGroup> object can be subclassed and used to create load files
101 :     that can then be loaded using the L<ERDBLoader.pl> command; however, there
102 : parrello 1.111 is no requirement that this be done.
103 :    
104 :     =head3 Constructors
105 :    
106 :     In order to use the load facility, the constructor for the database object
107 : parrello 1.123 must be able to function with no parameters or with the parameters construed
108 :     as a hash. The following options are used by the ERDB load facility. It is
109 :     not necessary to support them all.
110 :    
111 :     =over 4
112 :    
113 :     =item DBD
114 :    
115 :     XML database definition file.
116 :    
117 :     =item dbName
118 :    
119 :     Name of the database to use.
120 :    
121 :     =item sock
122 :    
123 :     Socket for accessing the database.
124 :    
125 :     =item userData
126 :    
127 :     Name and password used to log on to the database, separated by a slash.
128 :    
129 :     =item dbhost
130 :    
131 :     Database host name.
132 :    
133 :     =back
134 : parrello 1.1
135 : parrello 1.111 =head2 Data Types, Queries and Filtering
136 : parrello 1.8
137 :     =head3 Data Types
138 :    
139 : parrello 1.111 The ERDB system supports many different data types. It is possible to
140 :     configure additional user-defined types by adding PERL modules to the
141 : parrello 1.123 code. Each new type must be a subclass of L<ERDBType>. Standard
142 : parrello 1.111 types are listed in the compile-time STANDARD_TYPES constant. Custom
143 : parrello 1.120 types should be listed in the C<$ERDBExtras::customERDBtypes> variable
144 : parrello 1.111 of the configuration file. The variable must be a list reference
145 :     containing the names of the ERDBType subclasses for the custom
146 :     types.
147 :    
148 :     To get complete documentation of all the types, use
149 :     the L</ShowDataTypes> method. The most common types are
150 : parrello 1.8
151 :     =over 4
152 :    
153 : parrello 1.111 =item int
154 :    
155 :     Signed whole number with a range of roughly negative 2 billion to positive
156 :     2 billion. Integers are stored in the database as a 32-bit binary number.
157 : parrello 1.8
158 : parrello 1.111 =item string
159 :    
160 :     Variable-length string, up to around 250 characters. Strings are stored in
161 :     the database as variable-length ASCII with some escaping.
162 : parrello 1.8
163 : parrello 1.111 =item text
164 : parrello 1.8
165 : parrello 1.111 Variable-length string, up to around 65000 characters. Text is stored in the
166 :     database as variable-length ASCII with some escaping. Only the first 250
167 :     characters can be indexed.
168 : parrello 1.8
169 : parrello 1.111 =item float
170 : parrello 1.60
171 : parrello 1.111 Double-precision floating-point number, ranging from roughly -10^-300
172 :     to 10^-300, with around 14 significant digits. Floating-point numbers
173 :     are stored in the database in IEEE 8-byte floating-point format.
174 : parrello 1.60
175 : parrello 1.8 =item date
176 :    
177 : parrello 1.111 Date/time value, in whole seconds. Dates are stored as a number of seconds
178 :     from the beginning of the Unix epoch (January 1, 1970) in Universal
179 :     Coordinated Time. This makes it identical to a date or time number in PERL,
180 :     Unix, or Windows.
181 :    
182 :     =back
183 :    
184 :     All data fields are converted when stored or retrieved using the
185 :     L</EncodeField> and L</DecodeField> methods. This allows us to store
186 :     very exotic data values such as string lists, images, and PERL objects. The
187 :     conversion is not, however, completely transparent because no conversion
188 :     is performed on the parameter values for the various L</Get>-based queries.
189 :     There is a good reason for this: you can specify general SQL expressions as
190 :     filters, and it's extremely difficult for ERDB to determine the data type of
191 :     a particular parameter. This topic is dealt with in more detail below.
192 : parrello 1.8
193 : parrello 1.111 =head3 Standard Field Name Format
194 :    
195 :     There are several places in which field names are specified by the caller.
196 :     The standard field name format is the name of the entity or relationship
197 :     followed by the field name in parentheses. In some cases there a particular
198 :     entity or relationship is considered the default. Fields in the default
199 :     object can be specified as an unmodified field name. For example,
200 : parrello 1.8
201 : parrello 1.111 Feature(species-name)
202 : parrello 1.104
203 : parrello 1.111 would specify the species name field for the C<Feature> entity. If the
204 :     C<Feature> table were the default, it could be specified as
205 : parrello 1.104
206 : parrello 1.111 species-name
207 : parrello 1.104
208 : parrello 1.111 without the object name. You may also use underscores in place of hyphens,
209 :     which can be syntactically more convenient in PERL programs.
210 : parrello 1.104
211 : parrello 1.111 species_name
212 : parrello 1.8
213 : parrello 1.111 In some cases, the object name may not be the actual name of an object
214 :     in the database. It could be an alias assigned by a query, or the converse
215 :     name of a relationship. Alias names and converse names are generally
216 :     specified in the object name list of a query method. The alias or converse
217 :     name used in the query method will be carried over in all parameters to the
218 :     method and any data value structures returned by the query. In most cases,
219 :     once you decide on a name for something in a query, the name will stick for
220 :     all data returned by the query.
221 : parrello 1.8
222 : parrello 1.111 =head3 Queries
223 : parrello 1.8
224 : parrello 1.111 Queries against the database are performed by variations of the L</Get> method.
225 :     This method has three parameters: the I<object name list>, the I<filter clause>,
226 :     and the I<parameter list>. There is a certain complexity involved in queries
227 :     that has evolved over a period of many years in which the needs of the
228 :     applications were balanced against a need for simplicity. In most cases, you
229 :     just list the objects used in the query, code a standard SQL filter clause with
230 : parrello 1.123 field names in the L</Standard Field Name Format>, and specify a list of
231 : parrello 1.111 parameters to plug in to the parameter marks. The use of the special field name
232 :     format and the list of object names spare you the pain of writing a C<FROM>
233 :     clause and worrying about joins. For example, here's a simple query to look up
234 :     all Features for a particular genome.
235 : parrello 1.8
236 : parrello 1.111 my $query = $erdb->Get('Genome HasFeature Feature', 'Genome(id) = ?', [$genomeID]);
237 : parrello 1.8
238 : parrello 1.111 For more complicated queries, see the rest of this section.
239 : parrello 1.44
240 : parrello 1.111 =head4 Object Name List
241 : parrello 1.44
242 : parrello 1.111 The I<object name list> specifies the names of the entities and relationships
243 :     that participate in the query. This includes every object used to filter the
244 :     query as well as every object from which data is expected. The ERDB engine will
245 :     automatically generate the join clauses required to make the query work, which
246 :     greatly simplifies the coding of the query. You can specify the object name
247 :     list using a list reference or a space-delimited string. The following two
248 :     calls are equivalent.
249 : parrello 1.8
250 : parrello 1.111 my $query = $erdb->Get(['Genome', 'UsesImage', 'Image'], $filter, \@parms);
251 : parrello 1.145
252 : parrello 1.111 my $query = $erdb->Get('Genome UsesImage Image', $filter, \@parms);
253 : parrello 1.8
254 : parrello 1.111 If you specify a string, you have a few more options.
255 : parrello 1.8
256 : parrello 1.111 =over 4
257 : parrello 1.8
258 : parrello 1.111 =item *
259 : parrello 1.8
260 : parrello 1.111 You can use the keyword C<AND> to start a new join chain with an object
261 :     further back in the list.
262 : parrello 1.8
263 : parrello 1.111 =item *
264 : parrello 1.8
265 : parrello 1.145 You can specify an object name more than once. If it is intended to
266 : parrello 1.111 be a different instance of the same object, simply put a number at the
267 :     end. Each distinct number indicates a distinct instance.
268 : parrello 1.8
269 : parrello 1.111 =item *
270 : parrello 1.42
271 : parrello 1.111 You can use the converse name of a relationship to make the object name list
272 :     read more like regular English.
273 : parrello 1.42
274 : parrello 1.8 =back
275 :    
276 : parrello 1.111 These requirements do not come up very often, but they can make a big differance.
277 :    
278 :     For example, let us say you are looking for a feature that has a role in a
279 :     particular subsystem and also belongs to a particular genome. You can't use
280 :    
281 :     my $query = $erdb->Get(['Feature', 'HasRoleInSubsystem', 'Subsystem', 'HasFeature', 'Genome'], $filter, \@parms);
282 :    
283 :     because you don't want to join the C<HasFeature> table to the subsystem table.
284 :     Instead, you use
285 :    
286 :     my $query = $erdb->Get("Feature HasRoleInSubsystem Subsystem AND Feature HasFeature Genome", $filter, \@parms);
287 :    
288 :     Now consider a taxonomy hierarchy using the entity C<Class> and the
289 :     relationship C<BelongsTo> and say you want to find all subclasses of a
290 :     particular class. If you code
291 :    
292 :     my $query = $erdb->Get("Class BelongsTo Class", 'Class(id) = ?', [$class])
293 :    
294 :     Then the query will only return the particular class, and only if it belongs
295 :     to itself. The following query finds every class that belongs to a particular
296 :     class.
297 :    
298 :     my $query = $erdb->Get("Class BelongsTo Class2", 'Class2(id) = ?', [$class]);
299 :    
300 :     This query does the converse. It finds every class belonging to a particular class.
301 :    
302 :     my $query = $erdb->Get("Class BelongsTo Class2", 'Class(id) = ?', [$class]);
303 :    
304 :     The difference is indicated by the field name used in the filter clause. Because
305 :     the first occurrence of C<Class> is specified in the filter rather than the
306 :     second occurrence (C<Class2>), the query is anchored on the from-side of the
307 :     relationship.
308 :    
309 :     =head4 Filter Clause
310 :    
311 :     The filter clause is an SQL WHERE clause (without the WHERE) to be used to filter
312 :     and sort the query. The WHERE clause can be parameterized with parameter markers
313 :     (C<?>). Each field used in the WHERE clause must be specified in
314 : parrello 1.123 L</Standard Field Name Format>. Any parameters specified in the filter clause should
315 : parrello 1.111 be added to the parameter list as additional parameters. The fields in a filter
316 :     clause can come from primary entity relations, relationship relations, or
317 :     secondary entity relations; however, all of the entities and relationships
318 :     involved must be included in the list of object names on the query. There is
319 :     never a default object name for filter clause fields.
320 :    
321 :     The filter clause can also specify a sort order. To do this, simply follow
322 :     the filter string with an ORDER BY clause. For example, the following filter
323 :     string gets all genomes for a particular genus and sorts them by species name.
324 :    
325 :     "Genome(genus) = ? ORDER BY Genome(species)"
326 :    
327 :     Note that the case is important. Only an uppercase "ORDER BY" with a single
328 :     space will be processed. The idea is to make it less likely to find the verb by
329 :     accident.
330 :    
331 :     The rules for field references in a sort order are the same as those for field
332 :     references in the filter clause in general; however, unpredictable things may
333 :     happen if a sort field is from an entity's secondary relation.
334 :    
335 :     Finally, you can limit the number of rows returned by adding a LIMIT clause. The
336 :     LIMIT must be the last thing in the filter clause, and it contains only the word
337 :     "LIMIT" followed by a positive number. So, for example
338 :    
339 :     "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
340 :    
341 :     will only return the first ten genomes for the specified genus. The ORDER BY
342 :     clause is not required. For example, to just get the first 10 genomes in the
343 :     B<Genome> table, you could use
344 :    
345 :     "LIMIT 10"
346 :    
347 :     as your filter clause.
348 :    
349 :     =head4 Parameter List
350 :    
351 :     The parameter list is a reference to a list of parameter values. The parameter
352 :     values are substituted for the parameter marks in the filter clause in strict
353 :     left-to-right order.
354 :    
355 :     In the parameter list for a filter clause, you must be aware of the proper
356 : parrello 1.145 data types and perform any necessary conversions manually. This is not normally
357 : parrello 1.111 a problem. Most of the time, you only query against simple numeric or string
358 :     fields, and you only need to convert a string if there's a possibility it has
359 :     exotic characters like tabs or new-lines in it. Sometimes, however, this is not
360 :     enough.
361 :    
362 :     When you are writing programs to query ERDB databases, you can call
363 :     L</EncodeField> directly, specifying a field name in the
364 : parrello 1.123 L</Standard Field Name Format>. The value will be converted as if it
365 : parrello 1.111 was being stored into a field of the specified type. Alternatively, you
366 :     can call L</encode>, specifying a data type name. Both of these techniques
367 :     are shown in the example below.
368 :    
369 :     my $query = $erdb->Get("Genome UsesImage Image",
370 :     "Image(png) = ? AND Genome(description) = ?",
371 :     [$erdb->EncodeFIeld('Image(png)', $myImage),
372 :     ERDB::encode(text => $myDescription)]);
373 :    
374 :     You can export the L</encode> method if you expect to be doing this a lot
375 :     and don't want to bother with the package name on the call.
376 :    
377 :     use ERDB qw(encode);
378 : parrello 1.145
379 : parrello 1.111 # ... much later ...
380 : parrello 1.145
381 : parrello 1.111 my $query = $erdb->Get("Genome UsesImage Image",
382 :     "Image(png) = ? AND Genome(description) = ?",
383 :     [$erdb->EncodeField('Image(png)', $myImage),
384 :     encode(text => $myDescription)]);
385 :    
386 :     =head2 XML Database Description
387 : parrello 1.42
388 : parrello 1.8 =head3 Global Tags
389 :    
390 : parrello 1.111 The entire database definition must be inside a B<Database> tag. The display
391 :     name of the database is given by the text associated with the B<Title> tag. The
392 :     display name is only used in the automated documentation. The entities and
393 : parrello 1.8 relationships are listed inside the B<Entities> and B<Relationships> tags,
394 : parrello 1.107 respectively. There is also a C<Shapes> tag that contains additional shapes to
395 : parrello 1.111 display on the database diagram, and an C<Issues> tag that describes general
396 :     things that need to be remembered. These last two are completely optional.
397 : parrello 1.8
398 : parrello 1.10 <Database>
399 :     <Title>... display title here...</Title>
400 : parrello 1.107 <Issues>
401 : parrello 1.113 ... comments here ...
402 : parrello 1.107 </Issues>
403 : parrello 1.113 <Regions>
404 :     ... region definitions here ...
405 :     </Regions>
406 : parrello 1.10 <Entities>
407 :     ... entity definitions here ...
408 :     </Entities>
409 :     <Relationships>
410 : parrello 1.107 ... relationship definitions here ...
411 : parrello 1.10 </Relationships>
412 : parrello 1.107 <Shapes>
413 :     ... shape definitions here ...
414 :     </Shapes>
415 : parrello 1.10 </Database>
416 : parrello 1.8
417 : parrello 1.113 =head3 Notes and Asides
418 :    
419 : parrello 1.111 Entities, relationships, shapes, indexes, and fields all allow text tags called
420 : parrello 1.107 B<Notes> and B<Asides>. Both these tags contain comments that appear when the
421 : parrello 1.111 database documentation is generated. In addition, the text inside the B<Notes>
422 :     tag will be shown as a tooltip when mousing over the diagram.
423 : parrello 1.8
424 : parrello 1.113 The following special codes allow a limited rich text capability in Notes and
425 :     Asides.
426 :    
427 : parrello 1.125 [b]...[/b]: Bold text
428 :    
429 :     [i]...[/i]: Italics
430 :    
431 :     [p]...[/p]: Paragraph
432 :    
433 :     [link I<href>]...[/link]: Hyperlink to the URL I<href>
434 :    
435 :     [list]...[*]...[*]...[/list]: Bullet list, with B<[*]> separating list elements.
436 : parrello 1.113
437 : parrello 1.8 =head3 Fields
438 :    
439 : parrello 1.111 Both entities and relationships have fields described by B<Field> tags. A
440 :     B<Field> tag can have B<Notes> associated with it. The complete set of B<Field>
441 :     tags for an object mus be inside B<Fields> tags.
442 : parrello 1.8
443 : parrello 1.10 <Entity ... >
444 :     <Fields>
445 :     ... Field tags ...
446 :     </Fields>
447 :     </Entity>
448 : parrello 1.8
449 :     The attributes for the B<Field> tag are as follows.
450 :    
451 :     =over 4
452 :    
453 :     =item name
454 :    
455 : parrello 1.111 Name of the field. The field name should contain only letters, digits, and
456 :     hyphens (C<->), and the first character should be a letter. Most underlying
457 :     databases are case-insensitive with the respect to field names, so a best
458 :     practice is to use lower-case letters only. Finally, the name
459 :     C<search-relevance> has special meaning for full-text searches and should not be
460 : parrello 1.70 used as a field name.
461 : parrello 1.8
462 :     =item type
463 :    
464 : parrello 1.111 Data type of the field.
465 : parrello 1.8
466 :     =item relation
467 :    
468 : parrello 1.111 Name of the relation containing the field. This should only be specified for
469 :     entity fields. The ERDB system does not support optional fields or
470 :     multi-occurring fields in the primary relation of an entity. Instead, they are
471 :     put into secondary relations. So, for example, in the C<Genome> entity, the
472 :     C<group-name> field indicates a special grouping used to select a subset of the
473 :     genomes. A given genome may not be in any groups or may be in multiple groups.
474 :     Therefore, C<group-name> specifies a relation value. The relation name specified
475 :     must be a valid table name. By convention, it is usually the entity name
476 :     followed by a qualifying word (e.g. C<GenomeGroup>). In an entity, the fields
477 :     without a relation attribute are said to belong to the I<primary relation>. This
478 :     relation has the same name as the entity itself.
479 : parrello 1.8
480 : parrello 1.70 =item searchable
481 :    
482 : parrello 1.111 If specified, then the field is a candidate for full-text searching. A single
483 :     full-text index will be created for each relation with at least one searchable
484 :     field in it. For best results, this option should only be used for string or
485 :     text fields.
486 : parrello 1.70
487 : parrello 1.73 =item special
488 :    
489 :     This attribute allows the subclass to assign special meaning for certain fields.
490 :     The interpretation is up to the subclass itself. Currently, only entity fields
491 :     can have this attribute.
492 :    
493 : parrello 1.107 =item default
494 :    
495 : parrello 1.111 This attribute specifies the default field value to be used while loading. The
496 : parrello 1.123 default value is used if no value is specified in an L</InsertObject> call or in
497 :     the L<ERDBLoadGroup/Put> call that generates the load file. If no default is
498 :     specified, then the field is required and must have a value specified in the
499 :     call.
500 : parrello 1.111
501 :     The default value is specified as a string, so it must be in an encoded
502 :     form.
503 : parrello 1.107
504 : parrello 1.157 =item null
505 :    
506 :     If C<1>, this attribute indicates that the field can have a null value. The
507 :     default is C<0>.
508 :    
509 : parrello 1.8 =back
510 :    
511 :     =head3 Indexes
512 :    
513 : parrello 1.111 An entity can have multiple alternate indexes associated with it. The fields in
514 :     an index must all be from the same relation. The alternate indexes assist in
515 :     searching on fields other than the entity ID. A relationship has at least two
516 :     indexes-- a I<to-index> and a I<from-index> that order the results when crossing
517 :     the relationship. For example, in the relationship C<HasContig> from C<Genome>
518 :     to C<Contig>, the from-index would order the contigs of a ganome, and the
519 :     to-index would order the genomes of a contig. In addition, it can have zero or
520 :     more alternate indexes. A relationship's index can only specify fields in the
521 :     relationship.
522 :    
523 :     The alternate indexes for an entity or relationship are listed inside the
524 :     B<Indexes> tag. The from-index of a relationship is specified using the
525 :     B<FromIndex> tag; the to-index is specified using the B<ToIndex> tag.
526 :    
527 : parrello 1.157 Be aware of the fact that in some versions of MySQL, the maximum size of an
528 :     index key is 1000 bytes. This means at most four normal-sized strings.
529 :    
530 :     The B<Index> tag has one optional attribute.
531 :    
532 :     =over 4
533 :    
534 :     =item unique
535 :    
536 :     If C<1>, then the index is unique. The default is C<0> (a non-unique index).
537 :    
538 :     =back
539 : parrello 1.111
540 :     Each index can contain a B<Notes> tag. In addition, it will have an
541 :     B<IndexFields> tag containing the B<IndexField> tags. The B<IndexField>
542 :     tags specify, in order, the fields used in the index. The attributes of an
543 :     B<IndexField> tag are as follows.
544 : parrello 1.8
545 :     =over 4
546 :    
547 :     =item name
548 :    
549 :     Name of the field.
550 :    
551 :     =item order
552 :    
553 :     Sort order of the field-- C<ascending> or C<descending>.
554 :    
555 :     =back
556 :    
557 : parrello 1.167 The B<FromIndex>, B<ToIndex> and B<Index> tags can have a B<unique> attribute.
558 :     If specified, the index will be generated as a unique index. The B<ToIndex>
559 :     for a one-to-many relationship is always unique.
560 : parrello 1.8
561 : parrello 1.113 =head3 Regions
562 :    
563 :     A large database may be too big to fit comfortably on a single page. When this
564 :     happens, you have the option of dividing the diagram into regions that are shown
565 :     one at a time. When regions are present, a combo box will appear on the diagram
566 :     allowing the user to select which region to show. Each entity, relationship, or
567 :     shape can have multiple B<RegionInfo> tags describing how it should be displayed
568 :     when a particular region is selected. The regions themselves are described by
569 :     a B<Region> tag with a single attribute-- B<name>-- that indicates the region
570 :     name. The tag can be empty, or can contain C<Notes> elements that provide useful
571 :     documentation.
572 :    
573 :     =over 4
574 :    
575 :     =item name
576 :    
577 :     Name of the region.
578 :    
579 :     =back
580 :    
581 :     =head3 Diagram
582 :    
583 :     The diagram tag allows you to specify options for generating a diagram. If the
584 :     tag is present, then it will be used to configure diagram display in the
585 : parrello 1.123 documentation widget (see L<ERDBPDocPage>). the tag has the following
586 : parrello 1.113 attributes. It should not have any content; that is, it is not a container
587 :     tag.
588 :    
589 :     =over 4
590 :    
591 :     =item width
592 :    
593 :     Width for the diagram, in pixels. The default is 750.
594 :    
595 :     =item height
596 :    
597 :     Height for the diagram, in pixels. The default is 800.
598 :    
599 :     =item ratio
600 :    
601 :     Ratio of shape height to width. The default is 0.62.
602 :    
603 :     =item size
604 :    
605 :     Width in pixels for each shape.
606 :    
607 :     =item nonoise
608 :    
609 :     If set to 1, there will be a white background instead of an NMPDR noise background.
610 :    
611 :     =item editable
612 :    
613 :     If set to 1, a dropdown box and buttons will appear that allow you to edit the diagram,
614 :     download your changes, and make it pretty for printing.
615 :    
616 :     =item fontSize
617 :    
618 :     Maximum font size to use, in points. The default is 16.
619 :    
620 :     =item download
621 :    
622 :     URL of the CGI script that downloads the diagram XML to the user's computer. The XML text
623 :     will be sent via the C<data> parameter and the default file name via the C<name>
624 :     parameter.
625 :    
626 :     =item margin
627 :    
628 :     Margin between adjacent shapes, in pixels. The default is 10.
629 :    
630 :     =back
631 :    
632 : parrello 1.107 =head3 DisplayInfo
633 :    
634 :     The B<DisplayInfo> tag is used to describe how an entity, relationship, or shape
635 : parrello 1.111 should be displayed when the XML file is used to generate an interactive
636 : parrello 1.113 diagram. A B<DisplayInfo> can have no elements, or it can have multiple
637 :     B<Region> elements inside. The permissible attributes are as follows.
638 : parrello 1.107
639 :     =over 4
640 :    
641 : parrello 1.111 =item link
642 :    
643 :     URL to which the user should be sent when clicking on the shape. For entities
644 :     and relationships, this defaults to the most likely location for the object
645 :     description in the generated documentation.
646 :    
647 : parrello 1.107 =item theme
648 :    
649 : parrello 1.113 The themes are C<black>, C<blue>, C<brown>, C<cyan>, C<gray>, C<green>,
650 :     C<ivory>, C<navy>, C<purple>, C<red>, and C<violet>. These indicate the color to
651 :     be used for the displayed object. The default is C<gray>.
652 : parrello 1.107
653 :     =item col
654 :    
655 : parrello 1.111 The number of the column in which the object should be displayed. Fractional
656 :     column numbers are legal, though it's best to round to a multiple of 0.5. Thus,
657 :     a column of C<4.5> would be centered between columns 4 and 5.
658 : parrello 1.107
659 :     =item row
660 :    
661 :     The number of the row in which the object should be displayed. Fractional row
662 :     numbers are allowed in the same manner as for columns.
663 :    
664 :     =item connected
665 :    
666 :     If C<1>, the object is visibly connected by lines to the other objects
667 :     identified in the C<from> and C<to> attributes. This value is ignored for
668 :     entities, which never have C<from> or C<to>.
669 :    
670 :     =item caption
671 :    
672 :     Caption to be displayed on the object. If omitted, it defaults to the object's
673 :     name. You may use spaces and C<\n> codes to make the caption prettier.
674 :    
675 :     =item fixed
676 :    
677 :     If C<1>, then the C<row> and C<col> attributes are used to position the
678 :     object, even if it has C<from> and C<to> attributes. Otherwise, the object is
679 :     placed in the midpoint between the C<from> and C<to> shapes.
680 :    
681 :     =back
682 :    
683 : parrello 1.113 =head3 RegionInfo
684 :    
685 :     For large diagrams, the B<DisplayInfo> tag may have one or more B<RegionInfo>
686 :     elements inside, each belonging to one or more named regions. (The named regions
687 :     are desribed by the B<Region> tag.) The diagrammer will create a drop-down box
688 :     that can be used to choose which region should be displayed. Each region tag has
689 :     a C<name> attribute indicating the region to which it belongs, plus any of the
690 :     attributes allowed on the B<DisplayInfo> tag. The name indicates the name of a
691 :     region in which the parent object should be displayed. The other attributes
692 :     override the corresponding attributes in the B<DisplayInfo> parent. An object
693 :     with no Region tags present will be displayed in all regions. There is a default
694 :     region with no name that consists only of objects displayed in all regions. An
695 :     object with no B<DisplayInfo> tag at all will not be displayed in any region.
696 :    
697 : parrello 1.8 =head3 Object and Field Names
698 :    
699 : parrello 1.111 By convention entity and relationship names use capital casing (e.g. C<Genome>
700 :     or C<HasRegionsIn>. Most underlying databases, however, are aggressively
701 :     case-insensitive with respect to relation names, converting them internally to
702 :     all-upper case or all-lower case.
703 :    
704 :     If syntax or parsing errors occur when you try to load or use an ERDB database,
705 :     the most likely reason is that one of your objects has an SQL reserved word as
706 :     its name. The list of SQL reserved words keeps increasing; however, most are
707 :     unlikely to show up as a noun or declarative verb phrase. The exceptions are
708 :     C<Group>, C<User>, C<Table>, C<Index>, C<Object>, C<Date>, C<Number>, C<Update>,
709 :     C<Time>, C<Percent>, C<Memo>, C<Order>, and C<Sum>. This problem can crop up in
710 :     field names as well.
711 :    
712 :     Every entity has a field called C<id> that acts as its primary key. Every
713 :     relationship has fields called C<from-link> and C<to-link> that contain copies
714 :     of the relevant entity IDs. These are essentially ERDB's reserved words, and
715 :     should not be used for user-defined field names.
716 : parrello 1.8
717 : parrello 1.107 =head3 Issues
718 :    
719 :     Issues are comments displayed at the top of the database documentation. They
720 :     have no effect on the database or the diagram. The C<Issue> tag is a text tag
721 :     with no attributes.
722 :    
723 : parrello 1.8 =head3 Entities
724 :    
725 : parrello 1.111 An entity is described by the B<Entity> tag. The entity can contain B<Notes> and
726 :     B<Asides>, an optional B<DisplayInfo> tag, an B<Indexes> tag containing one or
727 :     more secondary indexes, and a B<Fields> tag containing one or more fields. The
728 :     attributes of the B<Entity> tag are as follows.
729 : parrello 1.8
730 :     =over 4
731 :    
732 :     =item name
733 :    
734 : parrello 1.111 Name of the entity. The entity name, by convention, uses capital casing (e.g.
735 :     C<Genome> or C<GroupBlock>) and should be a noun or noun phrase.
736 : parrello 1.8
737 :     =item keyType
738 :    
739 :     Data type of the primary key. The primary key is always named C<id>.
740 :    
741 : parrello 1.115 =item autonumber
742 :    
743 :     A value of C<1> means that after the entity's primary relation is loaded, the ID
744 :     field will be set to autonumber, so that new records inserted will have
745 :     automatic keys generated. Use this option with care. Once the relation is loaded,
746 :     it cannot be reloaded unless the table is first dropped and re-created. In addition,
747 :     the key must be an integer type.
748 :    
749 : parrello 1.8 =back
750 :    
751 :     =head3 Relationships
752 :    
753 : parrello 1.111 A relationship is described by the B<Relationship> tag. Within a relationship,
754 :     there can be B<DisplayInfo>, B<Notes> and B<Asides> tags, a B<Fields> tag
755 :     containing the intersection data fields, a B<FromIndex> tag containing the
756 :     index used to cross the relationship in the forward direction, a B<ToIndex> tag
757 :     containing the index used to cross the relationship in reverse, and an
758 :     C<Indexes> tag containing the alternate indexes.
759 : parrello 1.8
760 : parrello 1.111 The B<Relationship> tag has the following attributes.
761 : parrello 1.8
762 :     =over 4
763 :    
764 :     =item name
765 :    
766 : parrello 1.111 Name of the relationship. The relationship name, by convention, uses capital
767 :     casing (e.g. C<ContainsRegionIn> or C<HasContig>), and should be a declarative
768 :     verb phrase, designed to fit between the from-entity and the to-entity (e.g.
769 : parrello 1.8 Block C<ContainsRegionIn> Genome).
770 :    
771 :     =item from
772 :    
773 :     Name of the entity from which the relationship starts.
774 :    
775 :     =item to
776 :    
777 :     Name of the entity to which the relationship proceeds.
778 :    
779 :     =item arity
780 :    
781 :     Relationship type: C<1M> for one-to-many and C<MM> for many-to-many.
782 :    
783 : parrello 1.107 =item converse
784 :    
785 :     A name to be used when travelling backward through the relationship. This
786 : parrello 1.111 value can be used in place of the real relationship name to make queries
787 :     more readable.
788 : parrello 1.107
789 : parrello 1.159 =item loose
790 :    
791 :     If TRUE (C<1>), then deletion of an entity instance on the B<from> side
792 :     will NOT cause deletion of the connected entity instances on the B<to>
793 :     side. All many-to-many relationships are automatically loose. A one-to-many
794 :     relationship is generally not loose, but specifying this attribute can make
795 :     it so.
796 :    
797 : parrello 1.107 =back
798 :    
799 :     =head3 Shapes
800 :    
801 :     Shapes are objects drawn on the database diagram that do not physically exist
802 :     in the database. Entities are always drawn as rectangles and relationships are
803 : parrello 1.111 always drawn as diamonds, but a shape can be either of those, an arrow, a
804 :     bidirectional arrow, or an oval. The B<Shape> tag can contain B<Notes>,
805 :     B<Asides>, and B<DisplayInfo> tags, and has the
806 : parrello 1.107 following attributes.
807 :    
808 :     =over 4
809 :    
810 :     =item type
811 :    
812 :     Type of shape: C<arrow> for an arrow, C<biarrow> for a bidirectional arrow,
813 :     C<oval> for an ellipse, C<diamond> for a diamond, and C<rectangle> for a
814 :     rectangle.
815 :    
816 :     =item from
817 :    
818 :     Object from which this object is oriented. If the shape is an arrow, it
819 : parrello 1.111 will point toward the from-object.
820 : parrello 1.107
821 :     =item to
822 :    
823 :     Object toward which this object is oriented. If the shape is an arrow, it
824 : parrello 1.111 will point away from the to-object.
825 : parrello 1.107
826 :     =item name
827 :    
828 :     Name of the shape. This is used by other shapes to identify it in C<from>
829 :     and C<to> directives.
830 :    
831 : parrello 1.8 =back
832 :    
833 : parrello 1.1 =cut
834 :    
835 :     # GLOBALS
836 :    
837 : parrello 1.111 # Table of information about our datatypes.
838 :     my $TypeTable;
839 :    
840 : parrello 1.113 my @StandardTypes = qw(ERDBTypeBoolean ERDBTypeChar ERDBTypeCounter ERDBTypeDate
841 :     ERDBTypeFloat ERDBTypeHashString ERDBTypeInteger ERDBTypeString
842 :     ERDBTypeText);
843 : parrello 1.1
844 :     # Table translating arities into natural language.
845 : parrello 1.111 my %ArityTable = ( '1M' => 'one-to-many',
846 : parrello 1.10 'MM' => 'many-to-many'
847 :     );
848 : parrello 1.1
849 : parrello 1.73 # Options for XML input and output.
850 :    
851 :     my %XmlOptions = (GroupTags => { Relationships => 'Relationship',
852 :     Entities => 'Entity',
853 :     Fields => 'Field',
854 :     Indexes => 'Index',
855 : parrello 1.98 IndexFields => 'IndexField',
856 :     Issues => 'Issue',
857 : parrello 1.113 Regions => 'Region',
858 : parrello 1.98 Shapes => 'Shape'
859 : parrello 1.73 },
860 :     KeyAttr => { Relationship => 'name',
861 :     Entity => 'name',
862 : parrello 1.98 Field => 'name',
863 :     Shape => 'name'
864 : parrello 1.73 },
865 :     SuppressEmpty => 1,
866 :     );
867 :    
868 :     my %XmlInOpts = (
869 : parrello 1.111 ForceArray => [qw(Field Index Issues IndexField Relationship Entity Shape)],
870 : parrello 1.73 ForceContent => 1,
871 :     NormalizeSpace => 2,
872 :     );
873 :     my %XmlOutOpts = (
874 :     RootName => 'Database',
875 :     XMLDecl => 1,
876 :     );
877 : parrello 1.1
878 : parrello 1.113 # Table for flipping between FROM and TO
879 :     my %FromTo = (from => 'to', to => 'from');
880 :    
881 : parrello 1.126 # Name of metadata table.
882 :     use constant METADATA_TABLE => '_metadata';
883 :    
884 : parrello 1.111 =head2 Special Methods
885 : parrello 1.1
886 :     =head3 new
887 :    
888 : parrello 1.112 my $database = ERDB->new($dbh, $metaFileName, %options);
889 : parrello 1.1
890 :     Create a new ERDB object.
891 :    
892 :     =over 4
893 :    
894 :     =item dbh
895 :    
896 : parrello 1.123 L<DBKernel> database object for the target database.
897 : parrello 1.1
898 :     =item metaFileName
899 :    
900 :     Name of the XML file containing the metadata.
901 :    
902 : parrello 1.112 =item options
903 :    
904 :     Hash of configuration options.
905 :    
906 : parrello 1.1 =back
907 :    
908 : parrello 1.112 The supported configuration options are as follows. Options not in this list
909 :     will be presumed to be relevant to the subclass and will be ignored.
910 :    
911 :     =over 4
912 :    
913 :     =item demandDriven
914 :    
915 :     If TRUE, the database will be configured for a I<forward-only cursor>. Instead
916 :     of caching the query results, the query results will be provided at the rate
917 :     in which they are demanded by the client application. This is less stressful
918 :     on memory and disk space, but means you cannot have more than one query active
919 :     at the same time.
920 :    
921 : parrello 1.113 =back
922 :    
923 : parrello 1.1 =cut
924 :    
925 :     sub new {
926 : parrello 1.10 # Get the parameters.
927 : parrello 1.95 my ($class, $dbh, $metaFileName, %options) = @_;
928 : parrello 1.111 # Insure we have a type table.
929 :     GetDataTypes();
930 : parrello 1.112 # See if we want to use demand-driven flow control for queries.
931 :     if ($options{demandDriven}) {
932 :     $dbh->set_demand_driven(1);
933 :     }
934 : parrello 1.143 # Get the quote character.
935 :     my $quote = "";
936 :     if (defined $dbh) {
937 :     $quote = $dbh->quote;
938 :     }
939 : parrello 1.10 # Create the object.
940 :     my $self = { _dbh => $dbh,
941 : parrello 1.113 _metaFileName => $metaFileName,
942 : parrello 1.121 _autonumbered => {},
943 : parrello 1.143 _quote => $quote
944 : parrello 1.10 };
945 : parrello 1.126 # Bless it.
946 : parrello 1.10 bless $self, $class;
947 : parrello 1.144 # Check for a load directory.
948 :     if ($options{loadDirectory}) {
949 :     $self->{loadDirectory} = $options{loadDirectory};
950 :     }
951 : parrello 1.126 # Load the meta-data. (We must be blessed before doing this, because it
952 :     # involves a virtual method.)
953 :     $self->{_metaData} = _LoadMetaData($self, $metaFileName, $options{externalDBD});
954 :     # Return the object.
955 : parrello 1.10 return $self;
956 : parrello 1.1 }
957 :    
958 : parrello 1.111 =head3 SplitKeywords
959 :    
960 :     my @keywords = ERDB::SplitKeywords($keywordString);
961 :    
962 :     This method returns a list of the positive keywords in the specified
963 :     keyword string. All of the operators will have been stripped off,
964 :     and if the keyword is preceded by a minus operator (C<->), it will
965 :     not be in the list returned. The idea here is to get a list of the
966 :     keywords the user wants to see. The list will be processed to remove
967 :     duplicates.
968 :    
969 :     It is possible to create a string that confuses this method. For example
970 : parrello 1.1
971 : parrello 1.111 frog toad -frog
972 : parrello 1.1
973 : parrello 1.111 would return both C<frog> and C<toad>. If this is a problem we can deal
974 :     with it later.
975 : parrello 1.1
976 :     =over 4
977 :    
978 : parrello 1.111 =item keywordString
979 :    
980 :     The keyword string to be parsed.
981 :    
982 :     =item RETURN
983 : parrello 1.1
984 : parrello 1.111 Returns a list of the words in the keyword string the user wants to
985 :     see.
986 : parrello 1.1
987 :     =back
988 :    
989 :     =cut
990 :    
991 : parrello 1.111 sub SplitKeywords {
992 : parrello 1.10 # Get the parameters.
993 : parrello 1.111 my ($keywordString) = @_;
994 :     # Make a safety copy of the string. (This helps during debugging.)
995 :     my $workString = $keywordString;
996 :     # Convert operators we don't care about to spaces.
997 :     $workString =~ tr/+"()<>/ /;
998 :     # Split the rest of the string along space boundaries. Note that we
999 :     # eliminate any words that are zero length or begin with a minus sign.
1000 :     my @wordList = grep { $_ && substr($_, 0, 1) ne "-" } split /\s+/, $workString;
1001 :     # Use a hash to remove duplicates.
1002 :     my %words = map { $_ => 1 } @wordList;
1003 :     # Return the result.
1004 :     return sort keys %words;
1005 :     }
1006 :    
1007 :     =head3 GetDatabase
1008 :    
1009 : parrello 1.119 my $erdb = ERDB::GetDatabase($name, $dbd, %parms);
1010 : parrello 1.111
1011 :     Return an ERDB object for the named database. It is assumed that the
1012 :     database name is also the name of a class for connecting to it.
1013 : parrello 1.45
1014 :     =over 4
1015 :    
1016 : parrello 1.111 =item name
1017 :    
1018 :     Name of the desired database.
1019 :    
1020 :     =item dbd
1021 :    
1022 :     Alternate DBD file to use when processing the database definition.
1023 :    
1024 : parrello 1.119 =item parms
1025 :    
1026 :     Additional command-line parameters.
1027 :    
1028 : parrello 1.111 =item RETURN
1029 : parrello 1.45
1030 : parrello 1.111 Returns an ERDB object for the named database.
1031 : parrello 1.45
1032 :     =back
1033 :    
1034 :     =cut
1035 :    
1036 : parrello 1.111 sub GetDatabase {
1037 : parrello 1.45 # Get the parameters.
1038 : parrello 1.119 my ($name, $dbd, %parms) = @_;
1039 : parrello 1.111 # Get access to the database's package.
1040 :     require "$name.pm";
1041 : parrello 1.119 # Plug in the DBD parameter (if any).
1042 : parrello 1.111 if (defined $dbd) {
1043 : parrello 1.119 $parms{DBD} = $dbd;
1044 : parrello 1.10 }
1045 : parrello 1.111 # Construct the desired object.
1046 :     my $retVal = eval("$name->new(%parms)");
1047 :     # Fail if we didn't get it.
1048 :     Confess("Error connecting to database \"$name\": $@") if $@;
1049 :     # Return the result.
1050 : parrello 1.45 return $retVal;
1051 : parrello 1.1 }
1052 :    
1053 : parrello 1.111 =head3 ParseFieldName
1054 : parrello 1.1
1055 : parrello 1.111 my ($tableName, $fieldName) = ERDB::ParseFieldName($string, $defaultName);
1056 : parrello 1.1
1057 : parrello 1.111 or
1058 : parrello 1.1
1059 : parrello 1.111 my $normalizedName = ERDB::ParseFieldName($string, $defaultName);
1060 : parrello 1.1
1061 :    
1062 : parrello 1.145 Analyze a standard field name to separate the object name part from the
1063 : parrello 1.111 field part.
1064 : parrello 1.95
1065 : parrello 1.111 =over 4
1066 : parrello 1.95
1067 : parrello 1.111 =item string
1068 : parrello 1.95
1069 : parrello 1.111 Standard field name string to be parsed.
1070 : parrello 1.95
1071 : parrello 1.111 =item defaultName (optional)
1072 : parrello 1.95
1073 : parrello 1.111 Default object name to be used if the object name is not specified in the
1074 :     input string.
1075 : parrello 1.95
1076 : parrello 1.111 =item RETURN
1077 : parrello 1.1
1078 : parrello 1.111 In list context, returns the table name followed by the base field name. In
1079 : parrello 1.125 scalar context, returns the field name in a normalized L</Standard Field Name Format>,
1080 : parrello 1.111 with underscores converted to hyphens and an object name present. If the
1081 :     parse fails, will return an undefined value.
1082 : parrello 1.1
1083 : parrello 1.111 =back
1084 : parrello 1.1
1085 :     =cut
1086 :    
1087 : parrello 1.111 sub ParseFieldName {
1088 : parrello 1.10 # Get the parameters.
1089 : parrello 1.111 my ($string, $defaultName) = @_;
1090 :     # Declare the return values.
1091 : parrello 1.115 my ($tableName, $fieldName);
1092 : parrello 1.111 # Get a copy of the input string with underscores converted to hyphens.
1093 :     my $realString = $string;
1094 :     $realString =~ tr/_/-/;
1095 :     # Parse the input string.
1096 : parrello 1.149 if ($realString =~ /^(\w+)\(([\w\-]+)\)$/) {
1097 : parrello 1.111 # It's a standard name. Return the pieces.
1098 :     ($tableName, $fieldName) = ($1, $2);
1099 : parrello 1.149 } elsif ($realString =~ /^[\w\-]+$/ && defined $defaultName) {
1100 : parrello 1.111 # It's a plain name, and we have a default table name.
1101 : parrello 1.115 ($tableName, $fieldName) = ($defaultName, $realString);
1102 : parrello 1.111 }
1103 :     # Return the results.
1104 :     if (wantarray()) {
1105 :     return ($tableName, $fieldName);
1106 :     } elsif (! defined $tableName) {
1107 :     return undef;
1108 :     } else {
1109 :     return "$tableName($fieldName)";
1110 : parrello 1.10 }
1111 : parrello 1.1 }
1112 :    
1113 : parrello 1.113 =head3 CountParameterMarks
1114 :    
1115 :     my $count = ERDB::CountParameterMarks($filterString);
1116 :    
1117 :     Return the number of parameter marks in the specified filter string.
1118 :    
1119 :     =over 4
1120 :    
1121 :     =item filterString
1122 :    
1123 :     ERDB filter clause to examine.
1124 :    
1125 :     =item RETURN
1126 :    
1127 :     Returns the number of parameter marks in the specified filter clause.
1128 :    
1129 :     =back
1130 :    
1131 :     =cut
1132 :    
1133 :     sub CountParameterMarks {
1134 :     # Get the parameters.
1135 :     my ($filterString) = @_;
1136 :     # Declare the return variable.
1137 :     my $retVal = 0;
1138 :     # Get a safety copy of the filter string.
1139 :     my $filterCopy = $filterString;
1140 :     # Remove all escaped quotes.
1141 :     $filterCopy =~ s/\\'//g;
1142 :     # Remove all quoted strings.
1143 :     $filterCopy =~ s/'[^']*'//g;
1144 :     # Count the question marks.
1145 :     while ($filterCopy =~ /\?/g) {
1146 :     $retVal++
1147 :     }
1148 :     # Return the result.
1149 :     return $retVal;
1150 :     }
1151 :    
1152 :    
1153 : parrello 1.111 =head2 Query Methods
1154 :    
1155 :     =head3 GetEntity
1156 : parrello 1.1
1157 : parrello 1.111 my $entityObject = $erdb->GetEntity($entityType, $ID);
1158 : parrello 1.1
1159 : parrello 1.111 Return an object describing the entity instance with a specified ID.
1160 : parrello 1.1
1161 :     =over 4
1162 :    
1163 : parrello 1.111 =item entityType
1164 : parrello 1.1
1165 : parrello 1.111 Entity type name.
1166 : parrello 1.1
1167 : parrello 1.111 =item ID
1168 : parrello 1.1
1169 : parrello 1.111 ID of the desired entity.
1170 : parrello 1.1
1171 : parrello 1.111 =item RETURN
1172 : parrello 1.18
1173 : parrello 1.123 Returns a L<ERDBObject> object representing the desired entity instance, or
1174 : parrello 1.111 an undefined value if no instance is found with the specified key.
1175 : parrello 1.18
1176 : parrello 1.1 =back
1177 :    
1178 :     =cut
1179 :    
1180 : parrello 1.111 sub GetEntity {
1181 : parrello 1.10 # Get the parameters.
1182 : parrello 1.111 my ($self, $entityType, $ID) = @_;
1183 :     # Encode the ID value.
1184 :     my $coded = $self->EncodeField("$entityType(id)", $ID);
1185 :     # Create a query.
1186 :     my $query = $self->Get($entityType, "$entityType(id) = ?", [$coded]);
1187 :     # Get the first (and only) object.
1188 :     my $retVal = $query->Fetch();
1189 :     if (T(3)) {
1190 :     if ($retVal) {
1191 :     Trace("Entity $entityType \"$ID\" found.");
1192 :     } else {
1193 :     Trace("Entity $entityType \"$ID\" not found.");
1194 :     }
1195 : parrello 1.10 }
1196 : parrello 1.111 # Return the result.
1197 :     return $retVal;
1198 : parrello 1.1 }
1199 :    
1200 : parrello 1.111 =head3 GetChoices
1201 :    
1202 :     my @values = $erdb->GetChoices($entityName, $fieldName);
1203 : parrello 1.31
1204 : parrello 1.111 Return a list of all the values for the specified field that are represented in
1205 :     the specified entity.
1206 : parrello 1.31
1207 : parrello 1.111 Note that if the field is not indexed, then this will be a very slow operation.
1208 : parrello 1.31
1209 :     =over 4
1210 :    
1211 : parrello 1.111 =item entityName
1212 : parrello 1.31
1213 : parrello 1.111 Name of an entity in the database.
1214 : parrello 1.31
1215 : parrello 1.111 =item fieldName
1216 : parrello 1.31
1217 : parrello 1.123 Name of a field belonging to the entity in L</Standard Field Name Format>.
1218 : parrello 1.31
1219 :     =item RETURN
1220 :    
1221 : parrello 1.111 Returns a list of the distinct values for the specified field in the database.
1222 : parrello 1.31
1223 :     =back
1224 :    
1225 :     =cut
1226 :    
1227 : parrello 1.111 sub GetChoices {
1228 : parrello 1.31 # Get the parameters.
1229 : parrello 1.111 my ($self, $entityName, $fieldName) = @_;
1230 :     # Get the entity data structure.
1231 :     my $entityData = $self->_GetStructure($entityName);
1232 :     # Get the field descriptor.
1233 :     my $fieldData = $self->_FindField($fieldName, $entityName);
1234 :     # Get the name of the relation containing the field.
1235 :     my $relation = $fieldData->{relation};
1236 :     # Fix up the field name.
1237 :     my $realName = _FixName($fieldData->{name});
1238 :     # Get the field type.
1239 :     my $type = $fieldData->{type};
1240 :     # Get the database handle.
1241 :     my $dbh = $self->{_dbh};
1242 :     # Query the database.
1243 : parrello 1.142 my $results = $dbh->SQL("SELECT DISTINCT $self->{_quote}$realName$self->{_quote} FROM $self->{_quote}$relation$self->{_quote}");
1244 : parrello 1.111 # Clean the results. They are stored as a list of lists,
1245 :     # and we just want the one list. Also, we want to decode the values.
1246 :     my @retVal = sort map { $TypeTable->{$type}->decode($_->[0]) } @{$results};
1247 :     # Return the result.
1248 :     return @retVal;
1249 : parrello 1.31 }
1250 :    
1251 : parrello 1.111 =head3 GetEntityValues
1252 : parrello 1.42
1253 : parrello 1.111 my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
1254 : parrello 1.42
1255 : parrello 1.111 Return a list of values from a specified entity instance. If the entity instance
1256 :     does not exist, an empty list is returned.
1257 : parrello 1.42
1258 :     =over 4
1259 :    
1260 : parrello 1.111 =item entityType
1261 :    
1262 :     Entity type name.
1263 :    
1264 :     =item ID
1265 :    
1266 :     ID of the desired entity.
1267 :    
1268 :     =item fields
1269 : parrello 1.42
1270 : parrello 1.123 List of field names in L</Standard_Field_Name_Format>.
1271 : parrello 1.42
1272 : parrello 1.111 =item RETURN
1273 : parrello 1.42
1274 : parrello 1.111 Returns a flattened list of the values of the specified fields for the specified entity.
1275 : parrello 1.42
1276 :     =back
1277 :    
1278 :     =cut
1279 : parrello 1.111
1280 :     sub GetEntityValues {
1281 : parrello 1.42 # Get the parameters.
1282 : parrello 1.111 my ($self, $entityType, $ID, $fields) = @_;
1283 :     # Get the specified entity.
1284 :     my $entity = $self->GetEntity($entityType, $ID);
1285 :     # Declare the return list.
1286 :     my @retVal = ();
1287 :     # If we found the entity, push the values into the return list.
1288 :     if ($entity) {
1289 :     push @retVal, $entity->Values($fields);
1290 : parrello 1.42 }
1291 : parrello 1.111 # Return the result.
1292 :     return @retVal;
1293 : parrello 1.42 }
1294 :    
1295 : parrello 1.111 =head3 GetAll
1296 :    
1297 :     my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
1298 : parrello 1.46
1299 : parrello 1.111 Return a list of values taken from the objects returned by a query. The first
1300 :     three parameters correspond to the parameters of the L</Get> method. The final
1301 :     parameter is a list of the fields desired from each record found by the query
1302 : parrello 1.123 in L</Standard Field Name Format>. The default object name is the first one in the
1303 : parrello 1.111 object name list.
1304 : parrello 1.46
1305 : parrello 1.111 The list returned will be a list of lists. Each element of the list will contain
1306 :     the values returned for the fields specified in the fourth parameter. If one of the
1307 :     fields specified returns multiple values, they are flattened in with the rest. For
1308 :     example, the following call will return a list of the features in a particular
1309 :     spreadsheet cell, and each feature will be represented by a list containing the
1310 :     feature ID followed by all of its essentiality determinations.
1311 : parrello 1.46
1312 : parrello 1.111 @query = $erdb->Get('ContainsFeature Feature'], "ContainsFeature(from-link) = ?",
1313 :     [$ssCellID], ['Feature(id)', 'Feature(essential)']);
1314 : parrello 1.46
1315 :     =over 4
1316 :    
1317 : parrello 1.111 =item objectNames
1318 :    
1319 :     List containing the names of the entity and relationship objects to be retrieved.
1320 : parrello 1.123 See L</Object Name List>.
1321 : parrello 1.111
1322 :     =item filterClause
1323 :    
1324 :     WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query.
1325 : parrello 1.123 See L</Filter Clause>.
1326 : parrello 1.46
1327 : parrello 1.111 =item parameterList
1328 : parrello 1.46
1329 : parrello 1.111 List of the parameters to be substituted in for the parameters marks
1330 : parrello 1.123 in the filter clause. See L</Parameter List>.
1331 : parrello 1.46
1332 : parrello 1.111 =item fields
1333 : parrello 1.46
1334 : parrello 1.111 List of the fields to be returned in each element of the list returned, or a
1335 :     string containing a space-delimited list of field names. The field names should
1336 : parrello 1.123 be in L</Standard Field Name Format>.
1337 : parrello 1.46
1338 : parrello 1.111 =item count
1339 : parrello 1.46
1340 : parrello 1.111 Maximum number of records to return. If omitted or 0, all available records will
1341 :     be returned.
1342 : parrello 1.46
1343 : parrello 1.111 =item RETURN
1344 : parrello 1.1
1345 : parrello 1.111 Returns a list of list references. Each element of the return list contains the
1346 :     values for the fields specified in the B<fields> parameter.
1347 : parrello 1.1
1348 : parrello 1.111 =back
1349 : parrello 1.1
1350 :     =cut
1351 : parrello 1.111 #: Return Type @@;
1352 :     sub GetAll {
1353 : parrello 1.10 # Get the parameters.
1354 : parrello 1.111 my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
1355 :     # Translate the parameters from a list reference to a list. If the parameter
1356 :     # list is a scalar we convert it into a singleton list.
1357 :     my @parmList = ();
1358 :     if (ref $parameterList eq "ARRAY") {
1359 :     Trace("GetAll parm list is an array.") if T(4);
1360 :     @parmList = @{$parameterList};
1361 :     } else {
1362 :     Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
1363 :     push @parmList, $parameterList;
1364 :     }
1365 :     # Insure the counter has a value.
1366 :     if (!defined $count) {
1367 :     $count = 0;
1368 :     }
1369 :     # Add the row limit to the filter clause.
1370 :     if ($count > 0) {
1371 :     $filterClause .= " LIMIT $count";
1372 :     }
1373 :     # Create the query.
1374 :     my $query = $self->Get($objectNames, $filterClause, \@parmList);
1375 :     # Set up a counter of the number of records read.
1376 :     my $fetched = 0;
1377 :     # Convert the field names to a list if they came in as a string.
1378 :     my $fieldList = (ref $fields ? $fields : [split /\s+/, $fields]);
1379 :     # Loop through the records returned, extracting the fields. Note that if the
1380 :     # counter is non-zero, we stop when the number of records read hits the count.
1381 :     my @retVal = ();
1382 :     while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
1383 :     my @rowData = $row->Values($fieldList);
1384 :     push @retVal, \@rowData;
1385 :     $fetched++;
1386 : parrello 1.10 }
1387 : parrello 1.111 # Return the resulting list.
1388 :     return @retVal;
1389 : parrello 1.1 }
1390 :    
1391 : parrello 1.111 =head3 Exists
1392 : parrello 1.75
1393 : parrello 1.111 my $found = $erdb->Exists($entityName, $entityID);
1394 : parrello 1.75
1395 : parrello 1.111 Return TRUE if an entity exists, else FALSE.
1396 : parrello 1.75
1397 :     =over 4
1398 :    
1399 :     =item entityName
1400 :    
1401 : parrello 1.111 Name of the entity type (e.g. C<Feature>) relevant to the existence check.
1402 :    
1403 :     =item entityID
1404 :    
1405 :     ID of the entity instance whose existence is to be checked.
1406 : parrello 1.75
1407 :     =item RETURN
1408 :    
1409 : parrello 1.111 Returns TRUE if the entity instance exists, else FALSE.
1410 : parrello 1.75
1411 :     =back
1412 :    
1413 :     =cut
1414 : parrello 1.111 #: Return Type $;
1415 :     sub Exists {
1416 : parrello 1.75 # Get the parameters.
1417 : parrello 1.111 my ($self, $entityName, $entityID) = @_;
1418 :     # Check for the entity instance.
1419 :     Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
1420 :     my $testInstance = $self->GetEntity($entityName, $entityID);
1421 :     # Return an existence indicator.
1422 :     my $retVal = ($testInstance ? 1 : 0);
1423 :     return $retVal;
1424 : parrello 1.75 }
1425 :    
1426 : parrello 1.111 =head3 GetCount
1427 :    
1428 :     my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
1429 :    
1430 :     Return the number of rows found by a specified query. This method would
1431 :     normally be used to count the records in a single table. For example,
1432 :    
1433 :     my $count = $erdb->GetCount('Genome', 'Genome(genus-species) LIKE ?',
1434 :     ['homo %']);
1435 :    
1436 :     would return the number of genomes for the genus I<homo>. It is conceivable,
1437 :     however, to use it to return records based on a join. For example,
1438 :    
1439 :     my $count = $erdb->GetCount('HasFeature Genome', 'Genome(genus-species) LIKE ?',
1440 :     ['homo %']);
1441 :    
1442 :     would return the number of features for genomes in the genus I<homo>. Note that
1443 :     only the rows from the first table are counted. If the above command were
1444 : parrello 1.75
1445 : parrello 1.111 my $count = $erdb->GetCount('Genome HasFeature', 'Genome(genus-species) LIKE ?',
1446 :     ['homo %']);
1447 : parrello 1.75
1448 : parrello 1.111 it would return the number of genomes, not the number of genome/feature pairs.
1449 : parrello 1.75
1450 :     =over 4
1451 :    
1452 : parrello 1.111 =item objectNames
1453 :    
1454 :     Reference to a list of the objects (entities and relationships) included in the
1455 :     query, or a string containing a space-delimited list of object names. See
1456 : parrello 1.123 L</ObjectNames>.
1457 : parrello 1.111
1458 :     =item filter
1459 : parrello 1.75
1460 : parrello 1.123 A filter clause for restricting the query. See L</Filter Clause>.
1461 : parrello 1.75
1462 : parrello 1.111 =item params
1463 : parrello 1.75
1464 : parrello 1.111 Reference to a list of the parameter values to be substituted for the parameter
1465 : parrello 1.123 marks in the filter. See L</Parameter List>.
1466 : parrello 1.75
1467 :     =item RETURN
1468 :    
1469 : parrello 1.111 Returns a count of the number of records in the first table that would satisfy
1470 :     the query.
1471 : parrello 1.75
1472 :     =back
1473 :    
1474 :     =cut
1475 :    
1476 : parrello 1.111 sub GetCount {
1477 : parrello 1.75 # Get the parameters.
1478 : parrello 1.111 my ($self, $objectNames, $filter, $params) = @_;
1479 :     # Insure the params argument is an array reference if the caller left it
1480 :     # off.
1481 :     if (! defined($params)) {
1482 :     $params = [];
1483 :     }
1484 : parrello 1.75 # Declare the return variable.
1485 :     my $retVal;
1486 : parrello 1.111 # Create the SQL command suffix to get the desired records.
1487 :     my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1488 :     $self->_SetupSQL($objectNames, $filter);
1489 :     # Get the object we're counting.
1490 :     my $firstObject = $mappedNameListRef->[0];
1491 :     # Find out if we're counting an entity or a relationship.
1492 :     my $countedField;
1493 :     if ($self->IsEntity($mappedNameHashRef->{$firstObject}->[0])) {
1494 :     $countedField = "id";
1495 :     } else {
1496 :     # For a relationship we count the to-link because it's usually more
1497 :     # numerous. Note we're automatically converting to the SQL form
1498 :     # of the field name (to_link vs. to-link), and we're not worried
1499 :     # about converses.
1500 :     $countedField = "to_link";
1501 :     }
1502 :     # Prefix it with text telling it we want a record count.
1503 : parrello 1.142 my $command = "SELECT COUNT($self->{_quote}$firstObject$self->{_quote}.$countedField) $suffix";
1504 : parrello 1.111 # Prepare and execute the command.
1505 :     my $sth = $self->_GetStatementHandle($command, $params);
1506 :     # Get the count value.
1507 :     ($retVal) = $sth->fetchrow_array();
1508 :     # Check for a problem.
1509 :     if (! defined($retVal)) {
1510 :     if ($sth->err) {
1511 :     # Here we had an SQL error.
1512 :     Confess("Error retrieving row count: " . $sth->errstr());
1513 :     } else {
1514 :     # Here we have no result.
1515 :     Confess("No result attempting to retrieve row count.");
1516 :     }
1517 : parrello 1.75 }
1518 :     # Return the result.
1519 :     return $retVal;
1520 :     }
1521 :    
1522 : parrello 1.111 =head3 GetList
1523 : parrello 1.75
1524 : parrello 1.111 my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
1525 : parrello 1.75
1526 : parrello 1.123 Return a list of L<ERDBObject> objects for the specified query.
1527 : parrello 1.75
1528 : parrello 1.111 This method is essentially the same as L</Get> except it returns a list of
1529 :     objects rather than a query object that can be used to get the results one
1530 :     record at a time. This is almost always preferable to L</Get> when the result
1531 :     list is a manageable size.
1532 : parrello 1.75
1533 :     =over 4
1534 :    
1535 : parrello 1.111 =item objectNames
1536 : parrello 1.75
1537 : parrello 1.111 Reference to a list containing the names of the entity and relationship objects
1538 :     to be retrieved, or a string containing a space-delimited list of object names.
1539 : parrello 1.123 See L</Object Name List>.
1540 : parrello 1.75
1541 : parrello 1.111 =item filterClause
1542 : parrello 1.75
1543 : parrello 1.111 WHERE clause (without the WHERE) to be used to filter and sort the query. See
1544 : parrello 1.123 L</Filter Clause>.
1545 : parrello 1.75
1546 : parrello 1.111 =item params
1547 : parrello 1.75
1548 : parrello 1.111 Reference to a list of parameter values to be substituted into the filter clause.
1549 : parrello 1.123 See L</Parameter List>.
1550 : parrello 1.75
1551 :     =item RETURN
1552 :    
1553 : parrello 1.123 Returns a list of L<ERDBObject> objects that satisfy the query conditions.
1554 : parrello 1.75
1555 :     =back
1556 :    
1557 :     =cut
1558 : parrello 1.111 #: Return Type @%
1559 :     sub GetList {
1560 : parrello 1.75 # Get the parameters.
1561 : parrello 1.111 my ($self, $objectNames, $filterClause, $params) = @_;
1562 :     # Declare the return variable.
1563 :     my @retVal = ();
1564 :     # Perform the query.
1565 :     my $query = $self->Get($objectNames, $filterClause, $params);
1566 :     # Loop through the results.
1567 :     while (my $object = $query->Fetch) {
1568 :     push @retVal, $object;
1569 : parrello 1.75 }
1570 :     # Return the result.
1571 : parrello 1.111 return @retVal;
1572 : parrello 1.75 }
1573 :    
1574 : parrello 1.111 =head3 Get
1575 : parrello 1.1
1576 : parrello 1.111 my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1577 : parrello 1.1
1578 : parrello 1.111 This method returns a query object for entities of a specified type using a
1579 :     specified filter.
1580 : parrello 1.1
1581 :     =over 4
1582 :    
1583 : parrello 1.111 =item objectNames
1584 :    
1585 :     List containing the names of the entity and relationship objects to be retrieved,
1586 : parrello 1.123 or a string containing a space-delimited list of names. See L</Object Name List>.
1587 : parrello 1.111
1588 :     =item filterClause
1589 : parrello 1.1
1590 : parrello 1.111 WHERE clause (without the WHERE) to be used to filter and sort the query. See
1591 : parrello 1.123 L</Filter Clause>.
1592 : parrello 1.1
1593 : parrello 1.111 =item params
1594 : parrello 1.1
1595 : parrello 1.111 Reference to a list of parameter values to be substituted into the filter
1596 : parrello 1.123 clause. See L</Parameter List>.
1597 : parrello 1.1
1598 :     =item RETURN
1599 :    
1600 : parrello 1.123 Returns an L</ERDBQuery> object that can be used to iterate through all of the
1601 : parrello 1.111 results.
1602 : parrello 1.1
1603 :     =back
1604 :    
1605 :     =cut
1606 :    
1607 : parrello 1.111 sub Get {
1608 : parrello 1.10 # Get the parameters.
1609 : parrello 1.111 my ($self, $objectNames, $filterClause, $params) = @_;
1610 :     # Process the SQL stuff.
1611 :     my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1612 :     $self->_SetupSQL($objectNames, $filterClause);
1613 :     # Create the query.
1614 : parrello 1.142 my $command = "SELECT " . join(", ", map { "$self->{_quote}$_$self->{_quote}.*" } @$mappedNameListRef) .
1615 :     " $suffix";
1616 : parrello 1.111 my $sth = $self->_GetStatementHandle($command, $params);
1617 :     # Now we create the relation map, which enables ERDBQuery to determine the
1618 :     # order, name and mapped name for each object in the query.
1619 :     my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1620 :     # Return the statement object.
1621 :     my $retVal = ERDBQuery::_new($self, $sth, \@relationMap);
1622 : parrello 1.10 return $retVal;
1623 : parrello 1.1 }
1624 :    
1625 : parrello 1.116 =head3 Prepare
1626 :    
1627 :     my $query = $erdb->Prepare($objects, $filterString, $parms);
1628 :    
1629 :     Prepare a query for execution but do not create a statement handle. This
1630 :     is useful if you have a query that you want to validate but you do not
1631 :     yet want to acquire the resources to run it.
1632 :    
1633 :     =over 4
1634 :    
1635 :     =item objects
1636 :    
1637 :     List containing the names of the entity and relationship objects to be retrieved,
1638 : parrello 1.123 or a string containing a space-delimited list of names. See L</Object Name List>.
1639 : parrello 1.116
1640 :     =item filterString
1641 :    
1642 :     WHERE clause (without the WHERE) to be used to filter and sort the query. See
1643 : parrello 1.123 L</Filter Clause>.
1644 : parrello 1.116
1645 :     =item parms
1646 :    
1647 :     Reference to a list of parameter values to be substituted into the filter
1648 : parrello 1.123 clause. See L</Parameter List>.
1649 : parrello 1.116
1650 :     =item RETURN
1651 :    
1652 : parrello 1.123 Returns an L<ERDBQuery> object that can be used to check field names
1653 : parrello 1.116 or that can be populated with artificial data.
1654 :    
1655 :     =back
1656 :    
1657 :     =cut
1658 :    
1659 :     sub Prepare {
1660 :     # Get the parameters.
1661 :     my ($self, $objects, $filterString, $parms) = @_;
1662 :     # Process the SQL stuff.
1663 :     my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1664 :     $self->_SetupSQL($objects, $filterString);
1665 :     # Create the query.
1666 :     my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1667 :     ".* $suffix";
1668 :     # Now we create the relation map, which enables ERDBQuery to determine the
1669 :     # order, name and mapped name for each object in the query.
1670 :     my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1671 :     # Create the query object without a statement handle.
1672 :     my $retVal = ERDBQuery::_new($self, undef, \@relationMap);
1673 :     # Cache the command and the parameters.
1674 :     $retVal->_Prepare($command, $parms);
1675 :     # Return the result.
1676 :     return $retVal;
1677 :     }
1678 :    
1679 : parrello 1.111 =head3 Search
1680 : parrello 1.23
1681 : parrello 1.111 my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1682 : parrello 1.1
1683 : parrello 1.111 Perform a full text search with filtering. The search will be against a
1684 :     specified object in the object name list. That object will get an extra field
1685 :     containing the search relevance. Note that except for the search expression, the
1686 :     parameters of this method are the same as those for L</Get> and follow the same
1687 :     rules.
1688 : parrello 1.1
1689 : parrello 1.111 =over 4
1690 : parrello 1.1
1691 : parrello 1.111 =item searchExpression
1692 : parrello 1.1
1693 : parrello 1.111 Boolean search expression for the text fields of the target object. The default
1694 :     mode for a Boolean search expression is OR, but we want the default to be AND,
1695 :     so we will add a C<+> operator to each word with no other operator before it.
1696 : parrello 1.1
1697 : parrello 1.111 =item idx
1698 : parrello 1.1
1699 : parrello 1.111 Name of the object to be searched in full-text mode. If the object name list is
1700 :     a list reference, you can also specify the index into the list.
1701 : parrello 1.1
1702 : parrello 1.111 =item objectNames
1703 : parrello 1.1
1704 : parrello 1.111 List containing the names of the entity and relationship objects to be retrieved,
1705 : parrello 1.123 or a string containing a space-delimited list of names. See L</Object Name List>.
1706 : parrello 1.1
1707 : parrello 1.111 =item filterClause
1708 : parrello 1.1
1709 : parrello 1.111 WHERE clause (without the WHERE) to be used to filter and sort the query. See
1710 : parrello 1.123 L</Filter Clause>.
1711 : parrello 1.102
1712 : parrello 1.111 =item params
1713 : parrello 1.100
1714 : parrello 1.111 Reference to a list of parameter values to be substituted into the filter
1715 : parrello 1.123 clause. See L</Parameter List>.
1716 : parrello 1.100
1717 :     =item RETURN
1718 :    
1719 : parrello 1.123 Returns an L<ERDBQuery> object for the specified search.
1720 : parrello 1.100
1721 :     =back
1722 :    
1723 :     =cut
1724 :    
1725 : parrello 1.111 sub Search {
1726 : parrello 1.100 # Get the parameters.
1727 : parrello 1.111 my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1728 : parrello 1.100 # Declare the return variable.
1729 : parrello 1.111 my $retVal;
1730 :     # Create a safety copy of the parameter list. Note we have to be careful to
1731 :     # insure a parameter list exists before we copy it.
1732 :     my @myParams = ();
1733 :     if (defined $params) {
1734 :     @myParams = @{$params};
1735 :     }
1736 :     # Get the first object's structure so we have access to the searchable fields.
1737 :     my $object1Name = ($idx =~ /^\d+$/ ? $objectNames->[$idx] : $idx);
1738 :     my $object1Structure = $self->_GetStructure($object1Name);
1739 :     # Get the field list.
1740 :     if (! exists $object1Structure->{searchFields}) {
1741 :     Confess("No searchable index for $object1Name.");
1742 : parrello 1.100 } else {
1743 : parrello 1.111 # Get the field list.
1744 :     my @fields = @{$object1Structure->{searchFields}};
1745 :     # Clean the search expression.
1746 :     my $actualKeywords = $self->CleanKeywords($searchExpression);
1747 :     Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1748 :     # We need two match expressions, one for the filter clause and one in
1749 :     # the query itself. Both will use a parameter mark, so we need to push
1750 :     # the search expression onto the front of the parameter list twice.
1751 :     unshift @myParams, $actualKeywords, $actualKeywords;
1752 :     # Build the match expression.
1753 :     my @matchFilterFields = map { "$object1Name." . _FixName($_) } @fields;
1754 :     my $matchClause = "MATCH (" . join(", ", @matchFilterFields) . ") AGAINST (? IN BOOLEAN MODE)";
1755 :     # Process the SQL stuff.
1756 :     my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1757 :     $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1758 :     # Create the query. Note that the match clause is inserted at the front of
1759 :     # the select fields.
1760 :     my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1761 :     ".* $suffix";
1762 :     my $sth = $self->_GetStatementHandle($command, \@myParams);
1763 :     # Now we create the relation map, which enables ERDBQuery to determine the order, name
1764 :     # and mapped name for each object in the query.
1765 :     my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1766 :     # Return the statement object.
1767 :     $retVal = ERDBQuery::_new($self, $sth, \@relationMap, $object1Name);
1768 : parrello 1.100 }
1769 : parrello 1.111 return $retVal;
1770 : parrello 1.100 }
1771 :    
1772 : parrello 1.111 =head3 GetFlat
1773 : parrello 1.100
1774 : parrello 1.111 my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1775 : parrello 1.73
1776 : parrello 1.111 This is a variation of L</GetAll> that asks for only a single field per record
1777 :     and returns a single flattened list.
1778 : parrello 1.73
1779 : parrello 1.111 =over 4
1780 : parrello 1.73
1781 : parrello 1.111 =item objectNames
1782 : parrello 1.73
1783 : parrello 1.111 List containing the names of the entity and relationship objects to be retrieved,
1784 : parrello 1.123 or a string containing a space-delimited list of names. See L</Object_Name_List>.
1785 : parrello 1.73
1786 : parrello 1.111 =item filterClause
1787 : parrello 1.73
1788 : parrello 1.111 WHERE clause (without the WHERE) to be used to filter and sort the query. See
1789 : parrello 1.123 L</Filter Clause>.
1790 : parrello 1.73
1791 : parrello 1.111 =item params
1792 : parrello 1.20
1793 : parrello 1.111 Reference to a list of parameter values to be substituted into the filter
1794 : parrello 1.123 clause. See L</Parameter List>.
1795 : parrello 1.20
1796 : parrello 1.111 =item field
1797 : parrello 1.20
1798 : parrello 1.111 Name of the field to be used to get the elements of the list returned. The
1799 :     default object name for this context is the first object name specified.
1800 : parrello 1.20
1801 :     =item RETURN
1802 :    
1803 : parrello 1.111 Returns a list of values.
1804 : parrello 1.20
1805 :     =back
1806 :    
1807 :     =cut
1808 :    
1809 : parrello 1.111 sub GetFlat {
1810 : parrello 1.20 # Get the parameters.
1811 : parrello 1.111 my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1812 :     # Construct the query.
1813 :     my $query = $self->Get($objectNames, $filterClause, $parameterList);
1814 :     # Create the result list.
1815 :     my @retVal = ();
1816 :     # Loop through the records, adding the field values found to the result list.
1817 :     while (my $row = $query->Fetch()) {
1818 :     push @retVal, $row->Value($field);
1819 :     }
1820 :     # Return the list created.
1821 :     return @retVal;
1822 : parrello 1.20 }
1823 :    
1824 : parrello 1.160 =head3 IsUsed
1825 :    
1826 :     my $flag = $erdb->IsUsed($relationName);
1827 :    
1828 :     Returns TRUE if the specified relation contains any records, else FALSE.
1829 :    
1830 :     =over 4
1831 :    
1832 :     =item relationName
1833 :    
1834 :     Name of the relation to check.
1835 :    
1836 :     =item RETURN
1837 :    
1838 :     Returns the number of records in the relation, which will be TRUE if the
1839 :     relation is nonempty and FALSE otherwise.
1840 :    
1841 :     =back
1842 :    
1843 :     =cut
1844 :    
1845 :     sub IsUsed {
1846 :     # Get the parameters.
1847 :     my ($self, $relationName) = @_;
1848 :     # Get the data base handle.
1849 :     my $dbh = $self->{_dbh};
1850 :     # Construct a query to count the records in the relation.
1851 :     my $cmd = "SELECT COUNT(*) FROM $self->{_quote}$relationName$self->{_quote}";
1852 :     my $results = $dbh->SQL($cmd);
1853 :     # We'll put the count in here.
1854 :     my $retVal = 0;
1855 :     if ($results && scalar @$results) {
1856 :     $retVal = $results->[0][0];
1857 :     }
1858 :     # Return the count.
1859 :     return $retVal;
1860 :     }
1861 : parrello 1.1
1862 : parrello 1.111 =head2 Documentation and Metadata Methods
1863 :    
1864 : parrello 1.113 =head3 ComputeFieldTable
1865 :    
1866 :     my ($header, $rows) = ERDB::ComputeFieldTable($wiki, $name, $fieldData);
1867 :    
1868 :     Generate the header and rows of a field table for an entity or
1869 :     relationship. The field table describes each field in the specified
1870 :     object.
1871 :    
1872 :     =over 4
1873 :    
1874 :     =item wiki
1875 :    
1876 : parrello 1.123 L<WikiTools> object (or equivalent) for rendering HTML or markup.
1877 : parrello 1.113
1878 :     =item name
1879 :    
1880 :     Name of the object whose field table is being generated.
1881 :    
1882 :     =item fieldData
1883 :    
1884 :     Field structure of the specified entity or relationship.
1885 :    
1886 :     =item RETURN
1887 :    
1888 :     Returns a reference to a list of the labels for the header row and
1889 :     a reference to a list of lists representing the table cells.
1890 :    
1891 :     =back
1892 :    
1893 :     =cut
1894 :    
1895 :     sub ComputeFieldTable {
1896 :     # Get the parameters.
1897 :     my ($wiki, $name, $fieldData) = @_;
1898 :     # We need to sort the fields. First comes the ID, then the
1899 :     # primary fields and the secondary fields.
1900 :     my %sorter;
1901 :     for my $field (keys %$fieldData) {
1902 :     # Get the field's descriptor.
1903 :     my $fieldInfo = $fieldData->{$field};
1904 :     # Determine whether or not we have a primary field.
1905 :     my $primary;
1906 :     if ($field eq 'id') {
1907 :     $primary = 'A';
1908 :     } elsif ($fieldInfo->{relation} eq $name) {
1909 :     $primary = 'B';
1910 :     } else {
1911 :     $primary = 'C';
1912 :     }
1913 :     # Form the sort key from the flag and the name.
1914 :     $sorter{$field} = "$primary$field";
1915 :     }
1916 :     # Create the header descriptor for the table.
1917 :     my @header = qw(Name Type Notes);
1918 :     # We'll stash the rows in here.
1919 :     my @rows;
1920 :     # Loop through the fields in their proper order.
1921 :     for my $field (Tracer::SortByValue(\%sorter)) {
1922 :     # Get the field's descriptor.
1923 :     my $fieldInfo = $fieldData->{$field};
1924 :     # Format the type.
1925 :     my $type = "$fieldInfo->{type}";
1926 : parrello 1.157 if ($fieldInfo->{null}) {
1927 :     $type .= " (nullable)";
1928 :     }
1929 : parrello 1.113 # Secondary fields have "C" as the first letter in
1930 :     # the sort value. If a field is secondary, we mark
1931 :     # it as an array.
1932 :     if ($sorter{$field} =~ /^C/) {
1933 :     $type .= " array";
1934 :     }
1935 :     # Format its table row.
1936 :     push @rows, [$field, $type, ObjectNotes($fieldInfo, $wiki)];
1937 :     }
1938 :     # Return the results.
1939 :     return (\@header, \@rows);
1940 :     }
1941 :    
1942 : parrello 1.111 =head3 FindEntity
1943 :    
1944 :     my $objectData = $erdb->FindEntity($name);
1945 : parrello 1.1
1946 : parrello 1.111 Return the structural descriptor of the specified entity, or an undefined
1947 :     value if the entity does not exist.
1948 : parrello 1.39
1949 : parrello 1.1 =over 4
1950 :    
1951 : parrello 1.111 =item name
1952 :    
1953 :     Name of the desired entity.
1954 : parrello 1.1
1955 : parrello 1.111 =item RETURN
1956 : parrello 1.1
1957 : parrello 1.111 Returns the definition structure for the specified entity, or C<undef>
1958 :     if the named entity does not exist.
1959 : parrello 1.1
1960 : parrello 1.111 =back
1961 : parrello 1.1
1962 : parrello 1.111 =cut
1963 : parrello 1.1
1964 : parrello 1.111 sub FindEntity {
1965 :     # Get the parameters.
1966 :     my ($self, $name) = @_;
1967 :     # Return the result.
1968 :     return $self->_FindObject(Entities => $name);
1969 :     }
1970 : parrello 1.30
1971 : parrello 1.111 =head3 FindRelationship
1972 : parrello 1.39
1973 : parrello 1.111 my $objectData = $erdb->FindRelationship($name);
1974 : parrello 1.39
1975 : parrello 1.111 Return the structural descriptor of the specified relationship, or an undefined
1976 :     value if the relationship does not exist.
1977 : parrello 1.39
1978 : parrello 1.111 =over 4
1979 : parrello 1.39
1980 : parrello 1.111 =item name
1981 : parrello 1.1
1982 : parrello 1.111 Name of the desired relationship.
1983 : parrello 1.1
1984 :     =item RETURN
1985 :    
1986 : parrello 1.111 Returns the definition structure for the specified relationship, or C<undef>
1987 :     if the named relationship does not exist.
1988 : parrello 1.1
1989 :     =back
1990 :    
1991 :     =cut
1992 :    
1993 : parrello 1.111 sub FindRelationship {
1994 : parrello 1.10 # Get the parameters.
1995 : parrello 1.111 my ($self, $name) = @_;
1996 :     # Return the result.
1997 :     return $self->_FindObject(Relationships => $name);
1998 : parrello 1.1 }
1999 :    
2000 : parrello 1.147 =head3 ComputeTargetEntity
2001 :    
2002 :     my $targetEntity = $erdb->ComputeTargetEntity($relationshipName);
2003 :    
2004 :     Return the target entity of a relationship. If the relationship's true
2005 :     name is specified, this is the source (from) entity. If its converse
2006 :     name is specified, this is the target (to) entity. The returned name is
2007 :     the one expected to follow the relationship name in an object name string.
2008 :    
2009 :     =over 4
2010 :    
2011 :     =item relationshipName
2012 :    
2013 :     The name of the relationship to be used to identify the target entity.
2014 :    
2015 :     =item RETURN
2016 :    
2017 :     Returns the name of the entity that would be found after crossing
2018 :     the relationship in the direction indicated by the chosen relationship
2019 :     name. If the relationship name is invalid, an undefined value will be
2020 :     returned.
2021 :    
2022 :     =back
2023 :    
2024 :     =cut
2025 :    
2026 :     sub ComputeTargetEntity {
2027 :     # Get the parameters.
2028 :     my ($self, $relationshipName) = @_;
2029 :     # Declare the return variable.
2030 :     my $retVal;
2031 :     # Look for it in the alias table.
2032 :     my $realName = $self->{_metaData}->{AliasTable}->{$relationshipName};
2033 :     # Only proceed if it was found.
2034 :     if (defined $realName) {
2035 :     # Get the relationship's from and to entities.
2036 :     my ($fromEntity, $toEntity) = $self->GetRelationshipEntities($realName);
2037 :     # Return the appropriate one.
2038 :     if ($realName eq $relationshipName) {
2039 :     $retVal = $toEntity;
2040 :     } else {
2041 :     $retVal = $fromEntity;
2042 :     }
2043 :     }
2044 :     # Return the entity name found.
2045 :     return $retVal;
2046 :     }
2047 :    
2048 : parrello 1.111 =head3 FindShape
2049 :    
2050 :     my $objectData = $erdb->FindShape($name);
2051 : parrello 1.78
2052 : parrello 1.111 Return the structural descriptor of the specified shape, or an undefined
2053 :     value if the shape does not exist.
2054 : parrello 1.78
2055 : parrello 1.111 =over 4
2056 : parrello 1.70
2057 : parrello 1.111 =item name
2058 : parrello 1.70
2059 : parrello 1.111 Name of the desired shape.
2060 : parrello 1.70
2061 : parrello 1.111 =item RETURN
2062 : parrello 1.70
2063 : parrello 1.111 Returns the definition structure for the specified shape, or C<undef>
2064 :     if the named shape does not exist.
2065 : parrello 1.70
2066 : parrello 1.111 =back
2067 : parrello 1.70
2068 : parrello 1.111 =cut
2069 : parrello 1.70
2070 : parrello 1.111 sub FindShape {
2071 :     # Get the parameters.
2072 :     my ($self, $name) = @_;
2073 :     # Return the result.
2074 :     return $self->_FindObject(Shapes => $name);
2075 :     }
2076 : parrello 1.70
2077 : parrello 1.145 =head3 GetObjectsTable
2078 : parrello 1.70
2079 : parrello 1.111 my $objectHash = $erdb->GetObjectsTable($type);
2080 : parrello 1.70
2081 : parrello 1.111 Return the metadata hash of objects of the specified type-- entity,
2082 :     relationship, or shape.
2083 : parrello 1.70
2084 : parrello 1.111 =over 4
2085 : parrello 1.70
2086 : parrello 1.111 =item type
2087 : parrello 1.70
2088 : parrello 1.111 Type of object desired-- C<entity>, C<relationship>, or C<shape>.
2089 : parrello 1.70
2090 :     =item RETURN
2091 :    
2092 : parrello 1.111 Returns a reference to a hash containing all metadata for database
2093 :     objects of the specified type. The hash maps object names to object
2094 :     descriptors. The descriptors represent a cleaned and normalized
2095 :     version of the definition XML. Specifically, all of the implied
2096 :     defaults are filled in.
2097 : parrello 1.70
2098 :     =back
2099 :    
2100 :     =cut
2101 :    
2102 : parrello 1.111 sub GetObjectsTable {
2103 : parrello 1.70 # Get the parameters.
2104 : parrello 1.111 my ($self, $type) = @_;
2105 :     # Return the result.
2106 :     return $self->{_metaData}->{ERDB::Plurals($type)};
2107 : parrello 1.70 }
2108 :    
2109 : parrello 1.111 =head3 Plurals
2110 : parrello 1.45
2111 : parrello 1.111 my $plural = ERDB::Plurals($singular);
2112 : parrello 1.45
2113 : parrello 1.111 Return the plural form of the specified object type (entity,
2114 :     relationship, or shape). This is extremely useful in generating
2115 :     documentation.
2116 : parrello 1.45
2117 :     =over 4
2118 :    
2119 : parrello 1.111 =item singular
2120 : parrello 1.45
2121 : parrello 1.111 Singular form of the specified object type.
2122 : parrello 1.45
2123 :     =item RETURN
2124 :    
2125 : parrello 1.111 Plural form of the specified object type, in capital case.
2126 : parrello 1.45
2127 :     =back
2128 :    
2129 :     =cut
2130 : parrello 1.111
2131 :     sub Plurals {
2132 : parrello 1.45 # Get the parameters.
2133 : parrello 1.111 my ($singular) = @_;
2134 :     # Convert to capital case.
2135 :     my $retVal = ucfirst $singular;
2136 :     # Handle a "y" at the end.
2137 :     $retVal =~ s/y$/ie/;
2138 :     # Add the "s".
2139 :     $retVal .= "s";
2140 :     # Return the result.
2141 :     return $retVal;
2142 : parrello 1.45 }
2143 :    
2144 : parrello 1.111 =head3 ReadMetaXML
2145 : parrello 1.73
2146 : parrello 1.111 my $rawMetaData = ERDB::ReadDBD($fileName);
2147 : parrello 1.73
2148 : parrello 1.111 This method reads a raw database definition XML file and returns it.
2149 :     Normally, the metadata used by the ERDB system has been processed and
2150 :     modified to make it easier to load and retrieve the data; however,
2151 :     this method can be used to get the data in its raw form.
2152 : parrello 1.73
2153 :     =over 4
2154 :    
2155 : parrello 1.111 =item fileName
2156 : parrello 1.73
2157 : parrello 1.111 Name of the XML file to read.
2158 : parrello 1.73
2159 :     =item RETURN
2160 :    
2161 : parrello 1.111 Returns a hash reference containing the raw XML data from the specified file.
2162 : parrello 1.73
2163 :     =back
2164 :    
2165 :     =cut
2166 :    
2167 : parrello 1.111 sub ReadMetaXML {
2168 : parrello 1.73 # Get the parameters.
2169 : parrello 1.111 my ($fileName) = @_;
2170 :     # Read the XML.
2171 :     my $retVal = XML::Simple::XMLin($fileName, %XmlOptions, %XmlInOpts);
2172 :     Trace("XML metadata loaded from file $fileName.") if T(1);
2173 : parrello 1.73 # Return the result.
2174 : parrello 1.111 return $retVal;
2175 : parrello 1.73 }
2176 :    
2177 : parrello 1.111 =head3 FieldType
2178 : parrello 1.32
2179 : parrello 1.111 my $type = $erdb->FieldType($string, $defaultName);
2180 : parrello 1.77
2181 : parrello 1.125 Return the L<ERDBType> object for the specified field.
2182 : parrello 1.32
2183 :     =over 4
2184 :    
2185 : parrello 1.111 =item string
2186 : parrello 1.32
2187 : parrello 1.125 Field name string to be parsed. See L</Standard Field Name Format>.
2188 : parrello 1.32
2189 : parrello 1.111 =item defaultName (optional)
2190 : parrello 1.32
2191 : parrello 1.111 Default object name to be used if the object name is not specified in the
2192 :     input string.
2193 : parrello 1.32
2194 : parrello 1.111 =item RETURN
2195 : parrello 1.32
2196 : parrello 1.111 Return the type object for the field's type.
2197 : parrello 1.32
2198 : parrello 1.111 =back
2199 :    
2200 :     =cut
2201 :    
2202 :     sub FieldType {
2203 :     # Get the parameters.
2204 :     my ($self, $string, $defaultName) = @_;
2205 :     # Get the field descriptor.
2206 :     my $fieldData = $self->_FindField($string, $defaultName);
2207 :     # Compute the type.
2208 :     my $retVal = $TypeTable->{$fieldData->{type}};
2209 :     # Return the result.
2210 :     return $retVal;
2211 :     }
2212 : parrello 1.32
2213 : parrello 1.111 =head3 IsSecondary
2214 : parrello 1.32
2215 : parrello 1.111 my $type = $erdb->IsSecondary($string, $defaultName);
2216 : parrello 1.32
2217 : parrello 1.111 Return TRUE if the specified field is in a secondary relation, else
2218 :     FALSE.
2219 : parrello 1.78
2220 :     =over 4
2221 :    
2222 : parrello 1.111 =item string
2223 :    
2224 : parrello 1.125 Field name string to be parsed. See L</Standard Field Name Format>.
2225 : parrello 1.111
2226 :     =item defaultName (optional)
2227 : parrello 1.78
2228 : parrello 1.111 Default object name to be used if the object name is not specified in the
2229 :     input string.
2230 : parrello 1.78
2231 : parrello 1.111 =item RETURN
2232 : parrello 1.78
2233 : parrello 1.111 Returns TRUE if the specified field is in a secondary relation, else FALSE.
2234 : parrello 1.78
2235 :     =back
2236 :    
2237 : parrello 1.32 =cut
2238 : parrello 1.111
2239 :     sub IsSecondary {
2240 : parrello 1.32 # Get the parameters.
2241 : parrello 1.111 my ($self, $string, $defaultName) = @_;
2242 :     # Get the field's name and object.
2243 :     my ($objName, $fieldName) = ERDB::ParseFieldName($string, $defaultName);
2244 :     # Retrieve its descriptor from the metadata.
2245 :     my $fieldData = $self->_FindField($fieldName, $objName);
2246 :     # Compare the table name to the object name.
2247 :     my $retVal = ($fieldData->{relation} ne $objName);
2248 : parrello 1.32 # Return the result.
2249 :     return $retVal;
2250 :     }
2251 :    
2252 : parrello 1.111 =head3 FindRelation
2253 : parrello 1.78
2254 : parrello 1.111 my $relData = $erdb->FindRelation($relationName);
2255 : parrello 1.78
2256 : parrello 1.111 Return the descriptor for the specified relation.
2257 : parrello 1.78
2258 :     =over 4
2259 :    
2260 : parrello 1.111 =item relationName
2261 : parrello 1.78
2262 : parrello 1.111 Name of the relation whose descriptor is to be returned.
2263 : parrello 1.78
2264 : parrello 1.111 =item RETURN
2265 : parrello 1.78
2266 : parrello 1.111 Returns the object that describes the relation's indexes and fields.
2267 : parrello 1.78
2268 :     =back
2269 :    
2270 :     =cut
2271 : parrello 1.111 sub FindRelation {
2272 : parrello 1.78 # Get the parameters.
2273 : parrello 1.111 my ($self, $relationName) = @_;
2274 :     # Get the relation's structure from the master relation table in the
2275 :     # metadata structure.
2276 :     my $metaData = $self->{_metaData};
2277 :     my $retVal = $metaData->{RelationTable}->{$relationName};
2278 :     # Return it to the caller.
2279 :     return $retVal;
2280 : parrello 1.78 }
2281 :    
2282 : parrello 1.111 =head3 GetRelationshipEntities
2283 : parrello 1.79
2284 : parrello 1.111 my ($fromEntity, $toEntity) = $erdb->GetRelationshipEntities($relationshipName);
2285 : parrello 1.79
2286 : parrello 1.111 Return the names of the source and target entities for a relationship. If
2287 :     the specified name is not a relationship, an empty list is returned.
2288 : parrello 1.79
2289 :     =over 4
2290 :    
2291 :     =item relationshipName
2292 :    
2293 : parrello 1.111 Name of the relevant relationship.
2294 : parrello 1.79
2295 : parrello 1.111 =item RETURN
2296 : parrello 1.79
2297 : parrello 1.111 Returns a two-element list. The first element is the name of the relationship's
2298 :     from-entity, and the second is the name of the to-entity. If the specified name
2299 :     is not for a relationship, both elements are undefined.
2300 : parrello 1.79
2301 :     =back
2302 :    
2303 :     =cut
2304 :    
2305 : parrello 1.111 sub GetRelationshipEntities {
2306 : parrello 1.79 # Get the parameters.
2307 : parrello 1.111 my ($self, $relationshipName) = @_;
2308 :     # Declare the return variable.
2309 :     my @retVal = (undef, undef);
2310 :     # Try to find the caller-specified name in the relationship table.
2311 :     my $relationships = $self->{_metaData}->{Relationships};
2312 :     if (exists $relationships->{$relationshipName}) {
2313 :     # We found it. Return the from and to.
2314 :     @retVal = map { $relationships->{$relationshipName}->{$_} } qw(from to);
2315 : parrello 1.79 }
2316 : parrello 1.111 # Return the results.
2317 :     return @retVal;
2318 : parrello 1.79 }
2319 :    
2320 : parrello 1.91
2321 : parrello 1.111 =head3 ValidateFieldName
2322 :    
2323 :     my $okFlag = ERDB::ValidateFieldName($fieldName);
2324 : parrello 1.91
2325 : parrello 1.111 Return TRUE if the specified field name is valid, else FALSE. Valid field names must
2326 :     be hyphenated words subject to certain restrictions.
2327 : parrello 1.91
2328 :     =over 4
2329 :    
2330 : parrello 1.111 =item fieldName
2331 : parrello 1.91
2332 : parrello 1.111 Field name to be validated.
2333 : parrello 1.91
2334 :     =item RETURN
2335 :    
2336 : parrello 1.111 Returns TRUE if the field name is valid, else FALSE.
2337 : parrello 1.91
2338 :     =back
2339 :    
2340 :     =cut
2341 :    
2342 : parrello 1.111 sub ValidateFieldName {
2343 : parrello 1.91 # Get the parameters.
2344 : parrello 1.111 my ($fieldName) = @_;
2345 :     # Declare the return variable. The field name is valid until we hear
2346 :     # differently.
2347 :     my $retVal = 1;
2348 :     # Look for bad stuff in the name.
2349 :     if ($fieldName =~ /--/) {
2350 :     # Here we have a doubled minus sign.
2351 :     Trace("Field name $fieldName has a doubled hyphen.") if T(1);
2352 :     $retVal = 0;
2353 :     } elsif ($fieldName !~ /^[A-Za-z]/) {
2354 :     # Here the field name is missing the initial letter.
2355 :     Trace("Field name $fieldName does not begin with a letter.") if T(1);
2356 :     $retVal = 0;
2357 : parrello 1.91 } else {
2358 : parrello 1.111 # Strip out the minus signs. Everything remaining must be a letter
2359 :     # or digit.
2360 :     my $strippedName = $fieldName;
2361 :     $strippedName =~ s/-//g;
2362 :     if ($strippedName !~ /^([a-z]|\d)+$/i) {
2363 :     Trace("Field name $fieldName contains illegal characters.") if T(1);
2364 : parrello 1.91 $retVal = 0;
2365 :     }
2366 :     }
2367 : parrello 1.111 # Return the result.
2368 :     return $retVal;
2369 :     }
2370 :    
2371 :     =head3 GetFieldTable
2372 :    
2373 :     my $fieldHash = $self->GetFieldTable($objectnName);
2374 :    
2375 :     Get the field structure for a specified entity or relationship.
2376 :    
2377 :     =over 4
2378 :    
2379 :     =item objectName
2380 :    
2381 :     Name of the desired entity or relationship.
2382 :    
2383 :     =item RETURN
2384 :    
2385 :     The table containing the field descriptors for the specified object.
2386 :    
2387 :     =back
2388 :    
2389 :     =cut
2390 :    
2391 :     sub GetFieldTable {
2392 :     # Get the parameters.
2393 :     my ($self, $objectName) = @_;
2394 :     # Get the descriptor from the metadata.
2395 :     my $objectData = $self->_GetStructure($objectName);
2396 :     # Return the object's field table.
2397 :     return $objectData->{Fields};
2398 :     }
2399 :    
2400 :     =head3 EstimateRowSize
2401 :    
2402 :     my $rowSize = $erdb->EstimateRowSize($relName);
2403 :    
2404 :     Estimate the row size of the specified relation. The estimated row size is
2405 :     computed by adding up the average length for each data type.
2406 :    
2407 :     =over 4
2408 :    
2409 :     =item relName
2410 :    
2411 :     Name of the relation whose estimated row size is desired.
2412 :    
2413 :     =item RETURN
2414 :    
2415 :     Returns an estimate of the row size for the specified relation.
2416 :    
2417 :     =back
2418 :    
2419 :     =cut
2420 :     #: Return Type $;
2421 :     sub EstimateRowSize {
2422 :     # Get the parameters.
2423 :     my ($self, $relName) = @_;
2424 :     # Declare the return variable.
2425 :     my $retVal = 0;
2426 :     # Find the relation descriptor.
2427 :     my $relation = $self->FindRelation($relName);
2428 :     # Get the list of fields.
2429 :     for my $fieldData (@{$relation->{Fields}}) {
2430 :     # Get the field type and add its length.
2431 :     my $fieldLen = $TypeTable->{$fieldData->{type}}->averageLength();
2432 :     $retVal += $fieldLen;
2433 :     }
2434 :     # Return the result.
2435 : parrello 1.91 return $retVal;
2436 :     }
2437 :    
2438 : parrello 1.70 =head3 SortNeeded
2439 :    
2440 : parrello 1.94 my $parms = $erdb->SortNeeded($relationName);
2441 : parrello 1.70
2442 :     Return the pipe command for the sort that should be applied to the specified
2443 :     relation when creating the load file.
2444 :    
2445 :     For example, if the load file should be sorted ascending by the first
2446 :     field, this method would return
2447 :    
2448 :     sort -k1 -t"\t"
2449 :    
2450 :     If the first field is numeric, the method would return
2451 :    
2452 :     sort -k1n -t"\t"
2453 :    
2454 :     =over 4
2455 :    
2456 :     =item relationName
2457 :    
2458 : parrello 1.111 Name of the relation to be examined. This could be an entity name, a relationship
2459 :     name, or the name of a secondary entity relation.
2460 : parrello 1.70
2461 : parrello 1.94 =item
2462 : parrello 1.70
2463 :     Returns the sort command to use for sorting the relation, suitable for piping.
2464 :    
2465 :     =back
2466 :    
2467 :     =cut
2468 :     #: Return Type $;
2469 :     sub SortNeeded {
2470 :     # Get the parameters.
2471 :     my ($self, $relationName) = @_;
2472 :     # Declare a descriptor to hold the names of the key fields.
2473 :     my @keyNames = ();
2474 :     # Get the relation structure.
2475 : parrello 1.107 my $relationData = $self->FindRelation($relationName);
2476 : parrello 1.108 # Get the relation's field list.
2477 :     my @fields = @{$relationData->{Fields}};
2478 : parrello 1.110 my @fieldNames = map { $_->{name} } @fields;
2479 : parrello 1.70 # Find out if the relation is a primary entity relation,
2480 :     # a relationship relation, or a secondary entity relation.
2481 :     my $entityTable = $self->{_metaData}->{Entities};
2482 :     my $relationshipTable = $self->{_metaData}->{Relationships};
2483 :     if (exists $entityTable->{$relationName}) {
2484 : parrello 1.108 # Here we have a primary entity relation. We sort on the ID, and the
2485 :     # ID only.
2486 : parrello 1.70 push @keyNames, "id";
2487 :     } elsif (exists $relationshipTable->{$relationName}) {
2488 : parrello 1.108 # Here we have a relationship. We sort using the FROM index followed by
2489 :     # the rest of the fields, in order. First, we get all of the fields in
2490 :     # a hash.
2491 : parrello 1.110 my %fieldsLeft = map { $_ => 1 } @fieldNames;
2492 : parrello 1.108 # Get the index.
2493 : parrello 1.75 my $index = $relationData->{Indexes}->{idxFrom};
2494 : parrello 1.108 # Loop through its fields.
2495 :     for my $keySpec (@{$index->{IndexFields}}) {
2496 :     # Mark this field as used. The field may have a modifier, so we only
2497 :     # take the part up to the first space.
2498 :     $keySpec =~ /^(\S+)/;
2499 :     $fieldsLeft{$1} = 0;
2500 :     push @keyNames, $keySpec;
2501 :     }
2502 :     # Push the rest of the fields on.
2503 : parrello 1.110 push @keyNames, grep { $fieldsLeft{$_} } @fieldNames;
2504 : parrello 1.70 } else {
2505 : parrello 1.108 # Here we have a secondary entity relation, so we have a sort on the whole
2506 :     # record. This essentially gives us a sort on the ID followed by the
2507 :     # secondary data field.
2508 : parrello 1.110 push @keyNames, @fieldNames;
2509 : parrello 1.70 }
2510 :     # Now we parse the key names into sort parameters. First, we prime the return
2511 :     # string.
2512 : parrello 1.120 my $retVal = "sort $ERDBExtras::sort_options -u -T\"$ERDBExtras::temp\" -t\"\t\" ";
2513 : parrello 1.70 # Loop through the keys.
2514 :     for my $keyData (@keyNames) {
2515 :     # Get the key and the ordering.
2516 :     my ($keyName, $ordering);
2517 :     if ($keyData =~ /^([^ ]+) DESC/) {
2518 :     ($keyName, $ordering) = ($1, "descending");
2519 :     } else {
2520 :     ($keyName, $ordering) = ($keyData, "ascending");
2521 :     }
2522 :     # Find the key's position and type.
2523 :     my $fieldSpec;
2524 :     for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
2525 :     my $thisField = $fields[$i];
2526 :     if ($thisField->{name} eq $keyName) {
2527 :     # Get the sort modifier for this field type. The modifier
2528 :     # decides whether we're using a character, numeric, or
2529 :     # floating-point sort.
2530 : parrello 1.111 my $modifier = $TypeTable->{$thisField->{type}}->sortType();
2531 : parrello 1.70 # If the index is descending for this field, denote we want
2532 :     # to reverse the sort order on this field.
2533 :     if ($ordering eq 'descending') {
2534 :     $modifier .= "r";
2535 :     }
2536 :     # Store the position and modifier into the field spec, which
2537 :     # will stop the inner loop. Note that the field number is
2538 :     # 1-based in the sort command, so we have to increment the
2539 :     # index.
2540 : parrello 1.100 my $realI = $i + 1;
2541 :     $fieldSpec = "$realI,$realI$modifier";
2542 : parrello 1.70 }
2543 :     }
2544 :     # Add this field to the sort command.
2545 :     $retVal .= " -k$fieldSpec";
2546 :     }
2547 :     # Return the result.
2548 :     return $retVal;
2549 :     }
2550 :    
2551 : parrello 1.111 =head3 SpecialFields
2552 : parrello 1.6
2553 : parrello 1.111 my %specials = $erdb->SpecialFields($entityName);
2554 : parrello 1.6
2555 : parrello 1.111 Return a hash mapping special fields in the specified entity to the value of their
2556 :     C<special> attribute. This enables the subclass to get access to the special field
2557 :     attributes without needed to plumb the internal ERDB data structures.
2558 : parrello 1.6
2559 :     =over 4
2560 :    
2561 : parrello 1.111 =item entityName
2562 : parrello 1.6
2563 : parrello 1.111 Name of the entity whose special fields are desired.
2564 : parrello 1.6
2565 :     =item RETURN
2566 :    
2567 : parrello 1.111 Returns a hash. The keys of the hash are the special field names, and the values
2568 :     are the values from each special field's C<special> attribute.
2569 : parrello 1.6
2570 :     =back
2571 :    
2572 :     =cut
2573 : parrello 1.111
2574 :     sub SpecialFields {
2575 : parrello 1.6 # Get the parameters.
2576 : parrello 1.111 my ($self, $entityName) = @_;
2577 : parrello 1.10 # Declare the return variable.
2578 : parrello 1.111 my %retVal = ();
2579 :     # Find the entity's data structure.
2580 :     my $entityData = $self->{_metaData}->{Entities}->{$entityName};
2581 :     # Loop through its fields, adding each special field to the return hash.
2582 :     my $fieldHash = $entityData->{Fields};
2583 :     for my $fieldName (keys %{$fieldHash}) {
2584 :     my $fieldData = $fieldHash->{$fieldName};
2585 :     if (exists $fieldData->{special}) {
2586 :     $retVal{$fieldName} = $fieldData->{special};
2587 :     }
2588 : parrello 1.10 }
2589 : parrello 1.6 # Return the result.
2590 : parrello 1.111 return %retVal;
2591 : parrello 1.6 }
2592 :    
2593 : parrello 1.107
2594 : parrello 1.111 =head3 GetTableNames
2595 : parrello 1.107
2596 : parrello 1.111 my @names = $erdb->GetTableNames;
2597 : parrello 1.107
2598 : parrello 1.111 Return a list of the relations required to implement this database.
2599 : parrello 1.107
2600 : parrello 1.111 =cut
2601 : parrello 1.107
2602 : parrello 1.111 sub GetTableNames {
2603 :     # Get the parameters.
2604 :     my ($self) = @_;
2605 :     # Get the relation list from the metadata.
2606 :     my $relationTable = $self->{_metaData}->{RelationTable};
2607 :     # Return the relation names.
2608 :     return keys %{$relationTable};
2609 :     }
2610 : parrello 1.107
2611 : parrello 1.111 =head3 GetEntityTypes
2612 : parrello 1.107
2613 : parrello 1.111 my @names = $erdb->GetEntityTypes;
2614 : parrello 1.107
2615 : parrello 1.111 Return a list of the entity type names.
2616 : parrello 1.107
2617 :     =cut
2618 :    
2619 : parrello 1.111 sub GetEntityTypes {
2620 :     # Get the database object.
2621 :     my ($self) = @_;
2622 :     # Get the entity list from the metadata object.
2623 :     my $entityList = $self->{_metaData}->{Entities};
2624 :     # Return the list of entity names in alphabetical order.
2625 :     return sort keys %{$entityList};
2626 : parrello 1.107 }
2627 :    
2628 : parrello 1.45
2629 : parrello 1.111 =head3 GetConnectingRelationships
2630 :    
2631 :     my @list = $erdb->GetConnectingRelationships($entityName);
2632 :    
2633 :     Return a list of the relationships connected to the specified entity.
2634 : parrello 1.45
2635 : parrello 1.111 =over 4
2636 : parrello 1.45
2637 : parrello 1.111 =item entityName
2638 : parrello 1.45
2639 : parrello 1.111 Entity whose connected relationships are desired.
2640 : parrello 1.45
2641 : parrello 1.111 =item RETURN
2642 : parrello 1.45
2643 : parrello 1.111 Returns a list of the relationships that originate from the entity.
2644 :     If the entity is on the I<from> end, it will return the relationship
2645 :     name. If the entity is on the I<to> end it will return the converse of
2646 :     the relationship name.
2647 : parrello 1.45
2648 : parrello 1.111 =back
2649 : parrello 1.45
2650 : parrello 1.111 =cut
2651 : parrello 1.45
2652 : parrello 1.111 sub GetConnectingRelationships {
2653 :     # Get the parameters.
2654 :     my ($self, $entityName) = @_;
2655 :     # Declare the return variable.
2656 :     my @retVal;
2657 :     # Get the relationship list.
2658 :     my $relationships = $self->{_metaData}->{Relationships};
2659 :     # Find the entity.
2660 :     my $entity = $self->{_metaData}->{Entities}->{$entityName};
2661 :     # Only proceed if the entity exists.
2662 :     if (! defined $entity) {
2663 :     Trace("Entity $entityName not found.") if T(3);
2664 :     } else {
2665 :     # Loop through the relationships.
2666 :     my @rels = keys %$relationships;
2667 :     Trace(scalar(@rels) . " relationships found in connection search.") if T(3);
2668 :     for my $relationshipName (@rels) {
2669 :     my $relationship = $relationships->{$relationshipName};
2670 :     if ($relationship->{from} eq $entityName) {
2671 :     # Here we have a forward relationship.
2672 :     push @retVal, $relationshipName;
2673 :     } elsif ($relationship->{to} eq $entityName) {
2674 :     # Here we have a backward relationship. In this case, the
2675 :     # converse relationship name is preferred if it exists.
2676 :     my $converse = $relationship->{converse} || $relationshipName;
2677 :     push @retVal, $converse;
2678 :     }
2679 :     }
2680 :     }
2681 :     # Return the result.
2682 :     return @retVal;
2683 :     }
2684 : parrello 1.45
2685 : parrello 1.111 =head3 GetConnectingRelationshipData
2686 : parrello 1.45
2687 : parrello 1.111 my ($froms, $tos) = $erdb->GetConnectingRelationshipData($entityName);
2688 : parrello 1.45
2689 : parrello 1.111 Return the relationship data for the specified entity. The return will be
2690 :     a two-element list, each element of the list a reference to a hash that
2691 :     maps relationship names to structures. The first hash will be
2692 :     relationships originating from the entity, and the second element a
2693 :     reference to a hash of relationships pointing to the entity.
2694 : parrello 1.45
2695 : parrello 1.111 =over 4
2696 : parrello 1.45
2697 : parrello 1.111 =item entityName
2698 : parrello 1.45
2699 : parrello 1.111 Name of the entity of interest.
2700 : parrello 1.45
2701 :     =item RETURN
2702 :    
2703 : parrello 1.111 Returns a two-element list, each list being a map of relationship names
2704 :     to relationship metadata structures. The first element lists relationships
2705 :     originating from the entity, and the second element lists relationships that
2706 :     point to the entity.
2707 : parrello 1.45
2708 :     =back
2709 :    
2710 :     =cut
2711 :    
2712 : parrello 1.111 sub GetConnectingRelationshipData {
2713 : parrello 1.45 # Get the parameters.
2714 : parrello 1.111 my ($self, $entityName) = @_;
2715 :     # Create a hash that holds the return values.
2716 :     my %retVal = (from => {}, to => {});
2717 :     # Get the relationship table in the metadata.
2718 :     my $relationships = $self->{_metaData}->{Relationships};
2719 :     # Loop through it twice, once for each direction.
2720 :     for my $direction (qw(from to)) {
2721 :     # Get the return hash for this direction.
2722 :     my $hash = $retVal{$direction};
2723 :     # Loop through the relationships, looking for our entity in the
2724 :     # current direction.
2725 :     for my $rel (keys %$relationships) {
2726 :     my $relData = $relationships->{$rel};
2727 :     if ($relData->{$direction} eq $entityName) {
2728 :     # Here we've found our entity, so we put it in the
2729 :     # return hash.
2730 :     $hash->{$rel} = $relData;
2731 :     }
2732 :     }
2733 : parrello 1.66 }
2734 : parrello 1.111 # Return the results.
2735 :     return ($retVal{from}, $retVal{to});
2736 :     }
2737 :    
2738 :     =head3 GetDataTypes
2739 :    
2740 :     my $types = ERDB::GetDataTypes();
2741 :    
2742 :     Return a table of ERDB data types. The table returned is a hash of
2743 : parrello 1.123 L</ERDBType> objects keyed by type name.
2744 : parrello 1.111
2745 :     =cut
2746 :    
2747 :     sub GetDataTypes {
2748 :     # Insure we have a type table.
2749 :     if (! defined $TypeTable) {
2750 :     # Get a list of the names of the standard type classes.
2751 :     my @types = @StandardTypes;
2752 :     # Add in the custom types, if any.
2753 : parrello 1.120 if (defined $ERDBExtras::customERDBtypes) {
2754 :     push @types, @$ERDBExtras::customERDBtypes;
2755 : parrello 1.111 }
2756 :     Trace("Type List: " . join(", ", @types)) if T(Types => 3);
2757 :     # Initialize the table.
2758 :     $TypeTable = {};
2759 :     # Loop through all of the types, creating the type objects.
2760 :     for my $type (@types) {
2761 :     # Create the type object.
2762 :     my $typeObject;
2763 :     eval {
2764 :     require "$type.pm";
2765 :     $typeObject = eval("$type->new()");
2766 :     };
2767 :     # Ensure we didn't have an error.
2768 :     if ($@) {
2769 :     Confess("Error building ERDB type table: $@");
2770 :     } else {
2771 :     # Add the type to the type table.
2772 :     $TypeTable->{$typeObject->name()} = $typeObject;
2773 :     }
2774 : parrello 1.45 }
2775 :     }
2776 : parrello 1.111 # Return the type table.
2777 :     return $TypeTable;
2778 : parrello 1.45 }
2779 :    
2780 : parrello 1.1
2781 : parrello 1.111 =head3 ShowDataTypes
2782 : parrello 1.1
2783 : parrello 1.111 my $markup = ERDB::ShowDataTypes($wiki, $erdb);
2784 :    
2785 :     Display a table of all the valid data types for this installation.
2786 : parrello 1.1
2787 :     =over 4
2788 :    
2789 : parrello 1.111 =item wiki
2790 :    
2791 : parrello 1.123 An object used to render the table, similar to L</WikiTools>.
2792 : parrello 1.1
2793 : parrello 1.111 =item erdb (optional)
2794 : parrello 1.1
2795 : parrello 1.111 If specified, an ERDB object for a specific database. Only types used by
2796 :     the database will be put in the table. If omitted, all types are returned.
2797 : parrello 1.1
2798 :    
2799 :     =back
2800 :    
2801 :     =cut
2802 :    
2803 : parrello 1.111 sub ShowDataTypes {
2804 :     my ($wiki, $erdb) = @_;
2805 :     # Compute the hash of types to display.
2806 :     my $typeHash = ();
2807 :     if (! defined $erdb) {
2808 :     # No ERDB object, so we list all the types.
2809 :     $typeHash = GetDataTypes();
2810 :     } else {
2811 :     # Here we must extract the types used in the ERDB object.
2812 :     for my $relationName ($erdb->GetTableNames()) {
2813 :     my $relationData = $erdb->FindRelation($relationName);
2814 :     for my $fieldData (@{$relationData->{Fields}}) {
2815 :     my $type = $fieldData->{type};
2816 : parrello 1.113 my $typeData = $TypeTable->{$type};
2817 :     if (! defined $typeData) {
2818 :     Confess("Invalid data type \"$type\" in relation $relationName.");
2819 :     } else {
2820 :     $typeHash->{$type} = $typeData;
2821 :     }
2822 : parrello 1.111 }
2823 :     }
2824 :     }
2825 :     # We'll build table rows in here. We start with the header.
2826 : parrello 1.113 my @rows = [qw(Type Indexable Sort Pos Format Description)];
2827 : parrello 1.111 # Loop through the types, generating rows.
2828 :     for my $type (sort keys %$typeHash) {
2829 :     # Get the type object.
2830 :     my $typeData = $typeHash->{$type};
2831 :     # Compute the indexing column.
2832 :     my $flag = $typeData->indexMod();
2833 :     if (! defined $flag) {
2834 :     $flag = "no";
2835 :     } elsif ($flag eq "") {
2836 :     $flag = "yes";
2837 :     } else {
2838 :     $flag = "prefix";
2839 :     }
2840 :     # Compute the sort type.
2841 :     my $sortType = $typeData->sortType();
2842 :     if ($sortType eq 'g' || $sortType eq 'n') {
2843 :     $sortType = "numeric";
2844 :     } else {
2845 :     $sortType = "alphabetic";
2846 :     }
2847 :     # Get the position (pretty-sort value).
2848 :     my $pos = $typeData->prettySortValue();
2849 : parrello 1.113 # Finally, the format.
2850 :     my $format = $typeData->objectType() || "scalar";
2851 : parrello 1.111 # Build the data row.
2852 : parrello 1.113 my $row = [$type, $flag, $sortType, $pos, $format, $typeData->documentation()];
2853 : parrello 1.111 # Put it into the table.
2854 :     push @rows, $row;
2855 : parrello 1.10 }
2856 : parrello 1.111 # Form up the table.
2857 :     my $retVal = $wiki->Table(@rows);
2858 : parrello 1.10 # Return the result.
2859 :     return $retVal;
2860 : parrello 1.1 }
2861 :    
2862 : parrello 1.111 =head3 IsEntity
2863 :    
2864 :     my $flag = $erdb->IsEntity($entityName);
2865 : parrello 1.1
2866 : parrello 1.111 Return TRUE if the parameter is an entity name, else FALSE.
2867 : parrello 1.1
2868 :     =over 4
2869 :    
2870 : parrello 1.111 =item entityName
2871 :    
2872 :     Object name to be tested.
2873 :    
2874 :     =item RETURN
2875 : parrello 1.1
2876 : parrello 1.111 Returns TRUE if the specified string is an entity name, else FALSE.
2877 : parrello 1.1
2878 :     =back
2879 :    
2880 :     =cut
2881 :    
2882 : parrello 1.111 sub IsEntity {
2883 : parrello 1.10 # Get the parameters.
2884 : parrello 1.111 my ($self, $entityName) = @_;
2885 :     # Test to see if it's an entity.
2886 :     return exists $self->{_metaData}->{Entities}->{$entityName};
2887 : parrello 1.1 }
2888 :    
2889 : parrello 1.111 =head3 GetSecondaryFields
2890 : parrello 1.51
2891 : parrello 1.111 my %fieldTuples = $erdb->GetSecondaryFields($entityName);
2892 : parrello 1.51
2893 : parrello 1.111 This method will return a list of the name and type of each of the secondary
2894 :     fields for a specified entity. Secondary fields are stored in two-column tables
2895 :     separate from the primary entity table. This enables the field to have no value
2896 :     or to have multiple values.
2897 : parrello 1.51
2898 :     =over 4
2899 :    
2900 : parrello 1.111 =item entityName
2901 : parrello 1.51
2902 : parrello 1.111 Name of the entity whose secondary fields are desired.
2903 : parrello 1.51
2904 : parrello 1.111 =item RETURN
2905 : parrello 1.51
2906 : parrello 1.111 Returns a hash mapping the field names to their field types.
2907 : parrello 1.51
2908 :     =back
2909 :    
2910 :     =cut
2911 :    
2912 : parrello 1.111 sub GetSecondaryFields {
2913 : parrello 1.51 # Get the parameters.
2914 : parrello 1.111 my ($self, $entityName) = @_;
2915 :     # Declare the return variable.
2916 :     my %retVal = ();
2917 :     # Look for the entity.
2918 :     my $table = $self->GetFieldTable($entityName);
2919 :     # Loop through the fields, pulling out the secondaries.
2920 :     for my $field (sort keys %{$table}) {
2921 :     if ($table->{$field}->{relation} ne $entityName) {
2922 :     # Here we have a secondary field.
2923 :     $retVal{$field} = $table->{$field}->{type};
2924 : parrello 1.51 }
2925 :     }
2926 : parrello 1.111 # Return the result.
2927 :     return %retVal;
2928 : parrello 1.51 }
2929 :    
2930 : parrello 1.111 =head3 GetFieldRelationName
2931 : parrello 1.1
2932 : parrello 1.111 my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
2933 : parrello 1.1
2934 : parrello 1.111 Return the name of the relation containing a specified field.
2935 : parrello 1.1
2936 : parrello 1.111 =over 4
2937 : parrello 1.1
2938 : parrello 1.111 =item objectName
2939 : parrello 1.1
2940 : parrello 1.111 Name of the entity or relationship containing the field.
2941 : parrello 1.1
2942 : parrello 1.111 =item fieldName
2943 : parrello 1.1
2944 : parrello 1.111 Name of the relevant field in that entity or relationship.
2945 : parrello 1.1
2946 : parrello 1.111 =item RETURN
2947 : parrello 1.1
2948 : parrello 1.111 Returns the name of the database relation containing the field, or C<undef> if
2949 :     the field does not exist.
2950 : parrello 1.1
2951 :     =back
2952 :    
2953 :     =cut
2954 :    
2955 : parrello 1.111 sub GetFieldRelationName {
2956 : parrello 1.10 # Get the parameters.
2957 : parrello 1.111 my ($self, $objectName, $fieldName) = @_;
2958 :     # Declare the return variable.
2959 :     my $retVal;
2960 :     # Get the object field table.
2961 :     my $table = $self->GetFieldTable($objectName);
2962 :     # Only proceed if the field exists.
2963 :     if (exists $table->{$fieldName}) {
2964 :     # Determine the name of the relation that contains this field.
2965 :     $retVal = $table->{$fieldName}->{relation};
2966 : parrello 1.10 }
2967 : parrello 1.111 # Return the result.
2968 :     return $retVal;
2969 : parrello 1.78 }
2970 :    
2971 : parrello 1.111 =head3 DumpMetaData
2972 : parrello 1.78
2973 : parrello 1.111 $erdb->DumpMetaData();
2974 : parrello 1.78
2975 : parrello 1.111 Return a dump of the metadata structure.
2976 : parrello 1.78
2977 : parrello 1.111 =cut
2978 : parrello 1.78
2979 : parrello 1.111 sub DumpMetaData {
2980 :     # Get the parameters.
2981 :     my ($self) = @_;
2982 :     # Dump the meta-data.
2983 :     return Data::Dumper::Dumper($self->{_metaData});
2984 :     }
2985 : parrello 1.78
2986 : parrello 1.111 =head3 GenerateWikiData
2987 : parrello 1.78
2988 : parrello 1.111 my @wikiLines = $erdb->GenerateWikiData($wiki);
2989 : parrello 1.78
2990 : parrello 1.111 Build a description of the database for a wiki. The database will be
2991 :     organized into a single page, with sections for each entity and relationship.
2992 :     The return value is a list of text lines.
2993 : parrello 1.78
2994 : parrello 1.111 The parameter must be an object that mimics the object-based interface of the
2995 : parrello 1.123 L</WikiTools> object. If it is omitted, L</WikiTools> is used.
2996 : parrello 1.78
2997 :     =cut
2998 :    
2999 : parrello 1.111 sub GenerateWikiData {
3000 : parrello 1.78 # Get the parameters.
3001 : parrello 1.111 my ($self, $wiki) = @_;
3002 :     # If there's no Wiki object, use the default one.
3003 : olson 1.139 require WikiTools;
3004 : parrello 1.111 $wiki = WikiTools->new() if ! defined $wiki;
3005 :     # We'll build the wiki text in here.
3006 :     my @retVal = ();
3007 :     # Get the metadata object.
3008 :     my $metadata = $self->{_metaData};
3009 :     # Get the title string. This will become the page name.
3010 :     my $title = $metadata->{Title}->{content};
3011 :     # Get the entity and relationship lists.
3012 :     my $entityList = $metadata->{Entities};
3013 :     my $relationshipList = $metadata->{Relationships};
3014 :     my $shapeList = $metadata->{Shapes};
3015 :     # Start with the introductory text.
3016 :     push @retVal, $wiki->Heading(2, "Introduction");
3017 :     if (my $notes = $metadata->{Notes}) {
3018 :     push @retVal, _WikiNote($notes->{content}, $wiki);
3019 :     }
3020 :     # Generate the issue list.
3021 :     if (my $issues = $metadata->{Issues}) {
3022 :     push @retVal, $wiki->Heading(3, 'Issues');
3023 :     push @retVal, $wiki->List(map { $_->{content} } @{$issues});
3024 :     }
3025 : parrello 1.113 # Generate the region list.
3026 :     if (my $regions = $metadata->{Regions}) {
3027 :     push @retVal, $wiki->Heading(3, 'Diagram Regions');
3028 :     for my $region (@$regions) {
3029 :     # Check for notes.
3030 :     my $notes = "";
3031 :     if ($region->{Notes}) {
3032 :     $notes = $region->{Notes}->{content};
3033 :     }
3034 :     # Put out the region name as a heading.
3035 :     push @retVal, $wiki->Heading(4, $region->{name});
3036 :     # Output the notes for the region.
3037 :     push @retVal, _WikiNote($notes, $wiki);
3038 :     }
3039 :     }
3040 : parrello 1.111 # Generate the type table.
3041 :     push @retVal, $wiki->Heading(2, "Data Types");
3042 :     push @retVal, ShowDataTypes($wiki, $self);
3043 :     # Start the entity section.
3044 :     push @retVal, $wiki->Heading(2, "Entities");
3045 :     # Loop through the entities. Note that unlike the situation with HTML, we
3046 :     # don't need to generate the table of contents manually, just the data
3047 :     # itself.
3048 :     for my $key (sort keys %$entityList) {
3049 :     # Create a header for this entity.
3050 :     push @retVal, "", $wiki->Heading(3, $key);
3051 :     # Get the entity data.
3052 :     my $entityData = $entityList->{$key};
3053 :     # Plant the notes here, if there are any.
3054 :     push @retVal, ObjectNotes($entityData, $wiki);
3055 :     # Now we list the entity's relationships (if any). First, we build a list
3056 :     # of the relationships relevant to this entity.
3057 :     my @rels = ();
3058 :     for my $rel (sort keys %$relationshipList) {
3059 :     my $relStructure = $relationshipList->{$rel};
3060 : parrello 1.113 # Find out if this relationship involves this entity.
3061 :     my $dir;
3062 :     if ($relStructure->{from} eq $key) {
3063 :     $dir ='from';
3064 :     } elsif ($relStructure->{to} eq $key) {
3065 :     $dir = 'to';
3066 :     }
3067 :     if ($dir) {
3068 : parrello 1.111 # Get the relationship sentence.
3069 : parrello 1.113 my $relSentence = _ComputeRelationshipSentence($wiki, $rel, $relStructure, $dir);
3070 :     # Add it to the relationship list.
3071 : parrello 1.111 push @rels, $relSentence;
3072 :     }
3073 :     }
3074 :     # Add the relationships as a Wiki list.
3075 :     push @retVal, $wiki->List(@rels);
3076 : parrello 1.113 # Finally, the field table.
3077 :     push @retVal, _WikiObjectTable($key, $entityData->{Fields}, $wiki);
3078 : parrello 1.111 }
3079 :     # Now the entities are documented. Next we do the relationships.
3080 :     push @retVal, $wiki->Heading(2, "Relationships");
3081 :     for my $key (sort keys %$relationshipList) {
3082 :     my $relationshipData = $relationshipList->{$key};
3083 :     # Create the relationship heading.
3084 :     push @retVal, $wiki->Heading(3, $key);
3085 :     # Describe the relationship arity. Note there's a bit of trickiness
3086 :     # involving recursive many-to-many relationships. In a normal
3087 :     # many-to-many we use two sentences to describe the arity (one for each
3088 :     # direction). This is a bad idea for a recursive relationship, since
3089 :     # both sentences will say the same thing.
3090 :     my $arity = $relationshipData->{arity};
3091 :     my $fromEntity = $relationshipData->{from};
3092 :     my $toEntity = $relationshipData->{to};
3093 :     my @listElements = ();
3094 :     if ($arity eq "11") {
3095 :     push @listElements, "Each " . $wiki->Bold($fromEntity) .
3096 :     " relates to at most one " . $wiki->Bold($toEntity) . ".";
3097 :     } else {
3098 :     push @listElements, "Each " . $wiki->Bold($fromEntity) .
3099 :     " relates to multiple " . $wiki->Bold(Tracer::Pluralize($toEntity)) . ".";
3100 :     if ($arity eq "MM" && $fromEntity ne $toEntity) {
3101 :     push @listElements, "Each " . $wiki->Bold($toEntity) .
3102 :     " relates to multiple " . $wiki->Bold(Tracer::Pluralize($fromEntity));
3103 :     }
3104 : parrello 1.78 }
3105 : parrello 1.113 if ($relationshipData->{converse}) {
3106 :     push @listElements, "Converse name is $relationshipData->{converse}."
3107 :     }
3108 : parrello 1.111 push @retVal, $wiki->List(@listElements);
3109 :     # Plant the notes here, if there are any.
3110 :     push @retVal, ObjectNotes($relationshipData, $wiki);
3111 : parrello 1.113 # Finally, the field table.
3112 :     push @retVal, _WikiObjectTable($key, $relationshipData->{Fields}, $wiki);
3113 : parrello 1.78 }
3114 : parrello 1.111 # Now loop through the miscellaneous shapes.
3115 :     if ($shapeList) {
3116 :     push @retVal, $wiki->Heading(2, "Miscellaneous");
3117 :     for my $shape (sort keys %$shapeList) {
3118 :     push @retVal, $wiki->Heading(3, $shape);
3119 :     my $shapeData = $shapeList->{$shape};
3120 :     push @retVal, ObjectNotes($shapeData, $wiki);
3121 : parrello 1.145 }
3122 : parrello 1.78 }
3123 : parrello 1.111 # All done. Return the lines.
3124 :     return @retVal;
3125 :     }
3126 :    
3127 :     =head3 ObjectNotes
3128 :    
3129 :     my @noteParagraphs = ERDB::ObjectNotes($objectData, $wiki);
3130 :    
3131 :     Return a list of the notes and asides for an entity or relationship in
3132 :     Wiki format.
3133 :    
3134 :     =over 4
3135 :    
3136 :     =item objectData
3137 :    
3138 :     The metadata for the desired entity or relationship.
3139 :    
3140 :     =item wiki
3141 :    
3142 :     Wiki object used to render text.
3143 :    
3144 :     =item RETURN
3145 :    
3146 :     Returns a list of text paragraphs in Wiki markup form.
3147 :    
3148 :     =back
3149 :    
3150 :     =cut
3151 :    
3152 :     sub ObjectNotes {
3153 :     # Get the parameters.
3154 :     my ($objectData, $wiki) = @_;
3155 :     # Declare the return variable.
3156 :     my @retVal;
3157 :     # Loop through the types of notes.
3158 :     for my $noteType (qw(Notes Asides)) {
3159 :     my $text = $objectData->{$noteType};
3160 :     if ($text) {
3161 : parrello 1.113 push @retVal, _WikiNote($text->{content}, $wiki);
3162 :     }
3163 :     }
3164 :     # Return the result.
3165 :     return @retVal;
3166 :     }
3167 :    
3168 :     =head3 CheckObjectNames
3169 :    
3170 :     my @errors = $erdb->CheckObjectNames($objectNameString);
3171 :    
3172 :     Check an object name string for errors. The return value will be a list
3173 :     of error messages. If no error is found, an empty list will be returned.
3174 :     This process does not guarantee a correct object name list, but it
3175 :     catches the most obvious errors without the need for invoking a
3176 :     full-blown L</Get> method.
3177 :    
3178 :     =over 4
3179 :    
3180 :     =item objectNameString
3181 :    
3182 :     An object name string, consisting of a space-delimited list of entity and
3183 :     relationship names.
3184 :    
3185 :     =item RETURN
3186 :    
3187 :     Returns an empty list if successful, and a list of error messages if the
3188 :     list is invalid.
3189 :    
3190 :     =back
3191 :    
3192 :     =cut
3193 :    
3194 :     sub CheckObjectNames {
3195 :     # Get the parameters.
3196 :     my ($self, $objectNameString) = @_;
3197 :     # Declare the return variable.
3198 :     my @retVal;
3199 :     # Separate the string into pieces.
3200 : parrello 1.155 my @objectNames = split m/\s+/, $objectNameString;
3201 : parrello 1.113 # Start in a blank state.
3202 :     my $currentObject;
3203 :     # Get the alias table.
3204 :     my $aliasTable = $self->{_metaData}->{AliasTable};
3205 :     # Loop through the object names.
3206 :     for my $objectName (@objectNames) {
3207 :     # If we have an AND, clear the current object.
3208 :     if ($objectName eq 'AND') {
3209 :     # Insure we don't have an AND at the beginning or after another AND.
3210 :     if (! defined $currentObject) {
3211 :     push @retVal, "An AND was found in the wrong place.";
3212 :     }
3213 :     # Clear the context.
3214 :     undef $currentObject;
3215 :     } else {
3216 :     # Here the user has specified an object name. Get
3217 :     # the root name.
3218 :     unless ($objectName =~ /([A-Za-z]+)(\d*)/) {
3219 :     # Here the name has bad characters in it. Note that an error puts
3220 :     # us into a blank state.
3221 :     push @retVal, "Invalid characters found in \"$objectName\".";
3222 :     undef $currentObject;
3223 :     } else {
3224 :     # Get the real name from the alias table.
3225 :     my $name = $aliasTable->{$1};
3226 :     if (! defined $name) {
3227 :     push @retVal, "Could not find an entity or relationship named \"$objectName\".";
3228 :     undef $currentObject;
3229 :     } else {
3230 :     # Okay, we've got the real entity or relationship name. Does it belong here?
3231 :     # That's only an issue if there is a previous value in $currentObject.
3232 :     if (defined $currentObject) {
3233 :     my $joinClause = $self->_JoinClause($currentObject, $name);
3234 :     if (! $joinClause) {
3235 :     push @retVal, "There is no connection between $currentObject and $name."
3236 :     }
3237 :     }
3238 :     # Save this object as the new current object.
3239 :     $currentObject = $name;
3240 :     }
3241 :     }
3242 : parrello 1.111 }
3243 : parrello 1.78 }
3244 : parrello 1.111 # Return the result.
3245 :     return @retVal;
3246 : parrello 1.1 }
3247 :    
3248 : parrello 1.113 =head3 GetTitle
3249 :    
3250 :     my $text = $erdb->GetTitle();
3251 :    
3252 :     Return the title for this database.
3253 :    
3254 :     =cut
3255 :    
3256 :     sub GetTitle {
3257 :     # Get the parameters.
3258 :     my ($self) = @_;
3259 :     # Declare the return variable.
3260 :     my $retVal = $self->{_metaData}->{Title};
3261 :     if (! $retVal) {
3262 :     # Here no title was supplied, so we make one up.
3263 :     $retVal = "Unknown Database";
3264 :     } else {
3265 :     # Extract the content of the title element. This is the real title.
3266 :     $retVal = $retVal->{content};
3267 :     }
3268 :     # Return the result.
3269 :     return $retVal;
3270 :     }
3271 :    
3272 :     =head3 GetDiagramOptions
3273 :    
3274 :     my $hash = $erdb->GetDiagramOptions();
3275 :    
3276 :     Return the diagram options structure for this database. The diagram
3277 :     options are used by the ERDB documentation widget to configure the
3278 :     database diagram. If the options are not present, an undefined value will
3279 :     be returned.
3280 :    
3281 :     =cut
3282 :    
3283 :     sub GetDiagramOptions {
3284 :     # Get the parameters.
3285 :     my ($self) = @_;
3286 :     # Extract the options element.
3287 :     my $retVal = $self->{_metaData}->{Diagram};
3288 :     # Return the result.
3289 :     return $retVal;
3290 :     }
3291 :    
3292 :     =head3 GetMetaFileName
3293 :    
3294 :     my $fileName = $erdb->GetMetaFileName();
3295 :    
3296 :     Return the name of the database definition file for this database.
3297 :    
3298 :     =cut
3299 :    
3300 :     sub GetMetaFileName {
3301 :     # Get the parameters.
3302 :     my ($self) = @_;
3303 :     # Return the result.
3304 :     return $self->{_metaFileName};
3305 :     }
3306 :    
3307 :    
3308 : parrello 1.111 =head2 Database Administration and Loading Methods
3309 :    
3310 : parrello 1.1 =head3 LoadTable
3311 :    
3312 : parrello 1.95 my $results = $erdb->LoadTable($fileName, $relationName, %options);
3313 : parrello 1.1
3314 : parrello 1.111 Load data from a tab-delimited file into a specified table, optionally
3315 :     re-creating the table first.
3316 : parrello 1.1
3317 :     =over 4
3318 :    
3319 :     =item fileName
3320 :    
3321 :     Name of the file from which the table data should be loaded.
3322 :    
3323 :     =item relationName
3324 :    
3325 :     Name of the relation to be loaded. This is the same as the table name.
3326 :    
3327 : parrello 1.95 =item options
3328 : parrello 1.1
3329 : parrello 1.95 A hash of load options.
3330 : parrello 1.1
3331 :     =item RETURN
3332 :    
3333 : parrello 1.28 Returns a statistical object containing a list of the error messages.
3334 : parrello 1.1
3335 :     =back
3336 :    
3337 : parrello 1.95 The permissible options are as follows.
3338 :    
3339 :     =over 4
3340 :    
3341 :     =item truncate
3342 :    
3343 :     If TRUE, then the table will be erased before loading.
3344 :    
3345 :     =item mode
3346 :    
3347 :     Mode in which the load should operate, either C<low_priority> or C<concurrent>.
3348 :     This option is only applicable to a MySQL database.
3349 :    
3350 :     =item partial
3351 :    
3352 :     If TRUE, then it is assumed that this is a partial load, and the table will not
3353 :     be analyzed and compacted at the end.
3354 :    
3355 : parrello 1.108 =item failOnError
3356 :    
3357 :     If TRUE, then when an error occurs, the process will be killed; otherwise, the
3358 :     process will stay alive, but a message will be put into the statistics object.
3359 :    
3360 : parrello 1.168 =item dup
3361 : parrello 1.167
3362 : parrello 1.168 If C<ignore>, duplicate rows will be ignored. If C<replace>, duplicate rows will
3363 :     replace previous instances. If omitted, duplicate rows will cause an error.
3364 : parrello 1.167
3365 : parrello 1.95 =back
3366 :    
3367 : parrello 1.1 =cut
3368 : parrello 1.160
3369 : parrello 1.1 sub LoadTable {
3370 : parrello 1.10 # Get the parameters.
3371 : parrello 1.95 my ($self, $fileName, $relationName, %options) = @_;
3372 : parrello 1.108 # Record any error message in here. If it's defined when we're done
3373 :     # and failOnError is set, we confess it.
3374 :     my $errorMessage;
3375 : parrello 1.10 # Create the statistical return object.
3376 :     my $retVal = _GetLoadStats();
3377 :     # Trace the fact of the load.
3378 :     Trace("Loading table $relationName from $fileName") if T(2);
3379 :     # Get the database handle.
3380 :     my $dbh = $self->{_dbh};
3381 : parrello 1.22 # Get the input file size.
3382 :     my $fileSize = -s $fileName;
3383 : parrello 1.10 # Get the relation data.
3384 : parrello 1.107 my $relation = $self->FindRelation($relationName);
3385 : parrello 1.10 # Check the truncation flag.
3386 : parrello 1.95 if ($options{truncate}) {
3387 : parrello 1.10 Trace("Creating table $relationName") if T(2);
3388 : parrello 1.19 # Compute the row count estimate. We take the size of the load file,
3389 : parrello 1.136 # divide it by the estimated row size, and then multiply by 8 to
3390 :     # leave extra room. We postulate a minimum row count of 10000 to
3391 : parrello 1.19 # prevent problems with incoming empty load files.
3392 :     my $rowSize = $self->EstimateRowSize($relationName);
3393 : parrello 1.94 my $estimate = $fileSize * 8 / $rowSize;
3394 : parrello 1.136 if ($estimate < 10000) {
3395 :     $estimate = 10000;
3396 : parrello 1.90 }
3397 : parrello 1.10 # Re-create the table without its index.
3398 : parrello 1.19 $self->CreateTable($relationName, 0, $estimate);
3399 : parrello 1.10 # If this is a pre-index DBMS, create the index here.
3400 :     if ($dbh->{_preIndex}) {
3401 :     eval {
3402 :     $self->CreateIndex($relationName);
3403 :     };
3404 :     if ($@) {
3405 :     $retVal->AddMessage($@);
3406 : parrello 1.108 $errorMessage = $@;
3407 : parrello 1.10 }
3408 :     }
3409 :     }
3410 : parrello 1.3 # Load the table.
3411 : parrello 1.10 my $rv;
3412 :     eval {
3413 : parrello 1.111 $rv = $dbh->load_table(file => $fileName, tbl => $relationName,
3414 : parrello 1.167 style => $options{mode}, 'local' => 'LOCAL',
3415 : parrello 1.168 dup => $options{dup} );
3416 : parrello 1.10 };
3417 :     if (!defined $rv) {
3418 : parrello 1.3 $retVal->AddMessage($@) if ($@);
3419 : parrello 1.108 $errorMessage = "Table load failed for $relationName using $fileName.";
3420 :     $retVal->AddMessage("$errorMessage: " . $dbh->error_message);
3421 : parrello 1.10 } else {
3422 : parrello 1.22 # Here we successfully loaded the table.
3423 :     my $size = -s $fileName;
3424 :     Trace("$size bytes loaded into $relationName.") if T(2);
3425 : parrello 1.108 $retVal->Add("bytes-loaded", $size);
3426 :     $retVal->Add("tables-loaded" => 1);
3427 : parrello 1.10 # If we're rebuilding, we need to create the table indexes.
3428 : parrello 1.95 if ($options{truncate}) {
3429 : parrello 1.70 # Indexes are created here for PostGres. For PostGres, indexes are
3430 :     # best built at the end. For MySQL, the reverse is true.
3431 :     if (! $dbh->{_preIndex}) {
3432 :     eval {
3433 :     $self->CreateIndex($relationName);
3434 :     };
3435 :     if ($@) {
3436 : parrello 1.108 $errorMessage = $@;
3437 :     $retVal->AddMessage($errorMessage);
3438 : parrello 1.70 }
3439 :     }
3440 :     # The full-text index (if any) is always built last, even for MySQL.
3441 : parrello 1.118 # First we need to see if this table HAS a full-text index. Only
3442 : parrello 1.70 # primary relations are allowed that privilege.
3443 : parrello 1.81 Trace("Checking for full-text index on $relationName.") if T(2);
3444 : parrello 1.70 if ($self->_IsPrimary($relationName)) {
3445 : parrello 1.82 $self->CreateSearchIndex($relationName);
3446 : parrello 1.10 }
3447 :     }
3448 :     }
3449 : parrello 1.108 if ($errorMessage && $options{failOnError}) {
3450 :     # Here the load failed and we want to error out.
3451 :     Confess($errorMessage);
3452 :     }
3453 : parrello 1.20 # Analyze the table to improve performance.
3454 : parrello 1.95 if (! $options{partial}) {
3455 :     Trace("Analyzing and compacting $relationName.") if T(3);
3456 : parrello 1.100 $self->Analyze($relationName);
3457 : parrello 1.95 }
3458 : parrello 1.61 Trace("$relationName load completed.") if T(3);
3459 : parrello 1.10 # Return the statistics.
3460 :     return $retVal;
3461 : parrello 1.1 }
3462 :    
3463 : parrello 1.115 =head3 InsertNew
3464 :    
3465 :     my $newID = $erdb->InsertNew($entityName, %fields);
3466 :    
3467 :     Insert a new entity into a table that uses sequential integer IDs. A new,
3468 :     unique ID will be computed automatically and returned to the caller.
3469 :    
3470 :     =over 4
3471 :    
3472 :     =item entityName
3473 :    
3474 :     Type of the entity being inserted. The entity must have an integer ID.
3475 :    
3476 :     =item fields
3477 :    
3478 :     Hash of field names to field values. Every field in the entity's primary relation
3479 :     should be specified.
3480 :    
3481 :     =item RETURN
3482 :    
3483 :     Returns the ID of the inserted entity.
3484 :    
3485 :     =back
3486 :    
3487 :     =cut
3488 :    
3489 :     sub InsertNew {
3490 :     # Get the parameters.
3491 :     my ($self, $entityName, %fields) = @_;
3492 :     # Declare the return variable.
3493 :     my $retVal;
3494 : parrello 1.118 # If this is our first insert, we update the ID field definition.
3495 :     if (! exists $self->{_autonumber}->{$entityName}) {
3496 :     # Check to see if this is an autonumbered entity.
3497 :     my $entityData = $self->FindEntity($entityName);
3498 :     if (! defined $entityData || ! $entityData->{autonumber}) {
3499 :     Confess("Cannot use InsertNew for a entity $entityName.");
3500 :     } else {
3501 :     # Create the alter table command.
3502 :     my $fieldString = $self->_FieldString($entityData->{Fields}->{id});
3503 : parrello 1.142 my $command = "ALTER TABLE $self->{_quote}$entityName$self->{_quote} CHANGE COLUMN id $fieldString AUTO_INCREMENT";
3504 : parrello 1.118 # Execute the command.
3505 :     my $dbh = $self->{_dbh};
3506 :     $dbh->SQL($command);
3507 :     # Insure we don't do this again.
3508 :     $self->{_autonumber}->{$entityName} = 1;
3509 :     }
3510 :     }
3511 : parrello 1.115 # Insert the entity.
3512 :     $self->InsertObject($entityName, %fields, id => undef);
3513 :     # Get the last ID inserted.
3514 :     my $dbh = $self->{_dbh};
3515 :     $retVal = $dbh->last_insert_id();
3516 :     # Return the result.
3517 :     return $retVal;
3518 :     }
3519 :    
3520 : parrello 1.108
3521 : parrello 1.100 =head3 Analyze
3522 :    
3523 :     $erdb->Analyze($tableName);
3524 :    
3525 :     Analyze and compact a table in the database. This is useful after a load
3526 :     to improve the performance of the indexes.
3527 :    
3528 :     =over 4
3529 :    
3530 :     =item tableName
3531 :    
3532 :     Name of the table to be analyzed and compacted.
3533 :    
3534 :     =back
3535 :    
3536 :     =cut
3537 :    
3538 :     sub Analyze {
3539 :     # Get the parameters.
3540 :     my ($self, $tableName) = @_;
3541 :     # Analyze the table.
3542 :     $self->{_dbh}->vacuum_it($tableName);
3543 :     }
3544 :    
3545 :     =head3 TruncateTable
3546 :    
3547 :     $erdb->TruncateTable($table);
3548 :    
3549 :     Delete all rows from a table quickly. This uses the built-in SQL
3550 :     C<TRUNCATE> statement, which effectively drops and re-creates a table
3551 :     with all its settings intact.
3552 :    
3553 :     =over 4
3554 :    
3555 :     =item table
3556 :    
3557 :     Name of the table to be cleared.
3558 :    
3559 :     =back
3560 :    
3561 :     =cut
3562 :    
3563 :     sub TruncateTable {
3564 :     # Get the parameters.
3565 :     my ($self, $table) = @_;
3566 :     # Get the database handle.
3567 :     my $dbh = $self->{_dbh};
3568 :     # Execute a truncation comment.
3569 : parrello 1.134 $dbh->truncate_table($table);
3570 : parrello 1.100 }
3571 :    
3572 : parrello 1.141 =head3 VerifyTable
3573 :    
3574 :     my $newFlag = $erdb->VerifyTable($table, $indexFlag, $estimatedRows);
3575 :    
3576 :     If the specified table does not exist, create it. This method will return TRUE
3577 :     if the table is created, else FALSE.
3578 :    
3579 :     =over 4
3580 :    
3581 :     =item table
3582 :    
3583 :     Name of the table to verify.
3584 :    
3585 :     =item indexFlag
3586 :    
3587 :     TRUE if the indexes for the relation should be created, else FALSE. If FALSE,
3588 :     L</CreateIndexes> must be called later to bring the indexes into existence.
3589 :    
3590 :     =item estimatedRows (optional)
3591 :    
3592 :     If specified, the estimated maximum number of rows for the relation. This
3593 :     information allows the creation of tables using storage engines that are
3594 :     faster but require size estimates, such as MyISAM.
3595 :    
3596 :     =item RETURN
3597 :    
3598 :     Returns TRUE if the table was created, FALSE if it already existed in the
3599 :     database.
3600 :    
3601 :     =back
3602 :    
3603 :     =cut
3604 :    
3605 :     sub VerifyTable {
3606 :     # Get the parameters.
3607 :     my ($self, $table, $indexFlag, $estimatedRows) = @_;
3608 :     # Declare the return variable.
3609 :     my $retVal;
3610 :     # Only proceed if the table does NOT exist.
3611 :     if (! $self->{_dbh}->table_exists($table)) {
3612 :     # Attempt to create the table.
3613 :     $self->CreateTable($table, $indexFlag, $estimatedRows);
3614 :     # Denote we did so.
3615 :     $retVal = 1;
3616 :     }
3617 :     # Return the determination indicator.
3618 :     return $retVal;
3619 :     }
3620 : parrello 1.100
3621 : parrello 1.82 =head3 CreateSearchIndex
3622 :    
3623 : parrello 1.94 $erdb->CreateSearchIndex($objectName);
3624 : parrello 1.82
3625 :     Check for a full-text search index on the specified entity or relationship object, and
3626 :     if one is required, rebuild it.
3627 :    
3628 :     =over 4
3629 :    
3630 :     =item objectName
3631 :    
3632 :     Name of the entity or relationship to be indexed.
3633 :    
3634 :     =back
3635 :    
3636 :     =cut
3637 :    
3638 :     sub CreateSearchIndex {
3639 :     # Get the parameters.
3640 :     my ($self, $objectName) = @_;
3641 :     # Get the relation's entity/relationship structure.
3642 :     my $structure = $self->_GetStructure($objectName);
3643 :     # Get the database handle.
3644 :     my $dbh = $self->{_dbh};
3645 :     Trace("Checking for search fields in $objectName.") if T(3);
3646 :     # Check for a searchable fields list.
3647 :     if (exists $structure->{searchFields}) {
3648 :     # Here we know that we need to create a full-text search index.
3649 :     # Get an SQL-formatted field name list.
3650 :     my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
3651 :     # Create the index. If it already exists, it will be dropped.
3652 :     $dbh->create_index(tbl => $objectName, idx => "search_idx",
3653 :     flds => $fields, kind => 'fulltext');
3654 :     Trace("Index created for $fields in $objectName.") if T(2);
3655 :     }
3656 :     }
3657 :    
3658 : parrello 1.73 =head3 DropRelation
3659 : parrello 1.1
3660 : parrello 1.94 $erdb->DropRelation($relationName);
3661 : parrello 1.1
3662 : parrello 1.73 Physically drop a relation from the database.
3663 : parrello 1.1
3664 :     =over 4
3665 :    
3666 : parrello 1.73 =item relationName
3667 : parrello 1.1
3668 : parrello 1.73 Name of the relation to drop. If it does not exist, this method will have
3669 :     no effect.
3670 : parrello 1.1
3671 :     =back
3672 :    
3673 :     =cut
3674 :    
3675 : parrello 1.73 sub DropRelation {
3676 : parrello 1.10 # Get the parameters.
3677 : parrello 1.73 my ($self, $relationName) = @_;
3678 :     # Get the database handle.
3679 :     my $dbh = $self->{_dbh};
3680 :     # Drop the relation. The method used here has no effect if the relation
3681 :     # does not exist.
3682 : parrello 1.74 Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3683 :     $dbh->drop_table(tbl => $relationName);
3684 : parrello 1.1 }
3685 :    
3686 : parrello 1.111 =head3 DumpRelations
3687 : parrello 1.78
3688 : parrello 1.111 $erdb->DumpRelations($outputDirectory);
3689 : parrello 1.78
3690 : parrello 1.111 Write the contents of all the relations to tab-delimited files in the specified directory.
3691 :     Each file will have the same name as the relation dumped, with an extension of DTX.
3692 : parrello 1.78
3693 :     =over 4
3694 :    
3695 : parrello 1.111 =item outputDirectory
3696 : parrello 1.78
3697 : parrello 1.111 Name of the directory into which the relation files should be dumped.
3698 : parrello 1.78
3699 :     =back
3700 :    
3701 :     =cut
3702 :    
3703 : parrello 1.111 sub DumpRelations {
3704 : parrello 1.78 # Get the parameters.
3705 : parrello 1.111 my ($self, $outputDirectory) = @_;
3706 :     # Now we need to run through all the relations. First, we loop through the entities.
3707 :     my $metaData = $self->{_metaData};
3708 :     my $entities = $metaData->{Entities};
3709 :     for my $entityName (keys %{$entities}) {
3710 :     my $entityStructure = $entities->{$entityName};
3711 :     # Get the entity's relations.
3712 :     my $relationList = $entityStructure->{Relations};
3713 :     # Loop through the relations, dumping them.
3714 :     for my $relationName (keys %{$relationList}) {
3715 : parrello 1.116 $self->_DumpRelation($outputDirectory, $relationName);
3716 : parrello 1.78 }
3717 :     }
3718 : parrello 1.111 # Next, we loop through the relationships.
3719 :     my $relationships = $metaData->{Relationships};
3720 :     for my $relationshipName (keys %{$relationships}) {
3721 :     # Dump this relationship's relation.
3722 : parrello 1.116 $self->_DumpRelation($outputDirectory, $relationshipName);
3723 : parrello 1.111 }
3724 : parrello 1.78 }
3725 :    
3726 : parrello 1.116 =head3 DumpTable
3727 :    
3728 :     my $count = $erdb->DumpTable($tableName, $directory);
3729 :    
3730 :     Dump the specified table to the named directory. This will create a load
3731 :     file having the same name as the relation with an extension of DTX. This
3732 :     file can then be used to reload the table at a later date. If the table
3733 : parrello 1.130 does not exist, no action will be taken.
3734 : parrello 1.116
3735 :     =over 4
3736 :    
3737 :     =item tableName
3738 :    
3739 :     Name of the table to dump.
3740 :    
3741 :     =item directory
3742 :    
3743 :     Name of the directory in which the dump file should be placed.
3744 :    
3745 :     =item RETURN
3746 :    
3747 :     Returns the number of records written.
3748 :    
3749 :     =back
3750 :    
3751 :     =cut
3752 :    
3753 :     sub DumpTable {
3754 :     # Get the parameters.
3755 :     my ($self, $tableName, $directory) = @_;
3756 :     # Declare the return variable.
3757 :     my $retVal;
3758 :     # Insure the table name is valid.
3759 : parrello 1.130 if (exists $self->{_metaData}->{RelationTable}->{$tableName}) {
3760 : parrello 1.116 # Call the internal dumper.
3761 :     $retVal = $self->_DumpRelation($directory, $tableName);
3762 :     }
3763 :     # Return the result.
3764 :     return $retVal;
3765 :     }
3766 :    
3767 :    
3768 : parrello 1.111 =head3 TypeDefault
3769 : parrello 1.6
3770 : parrello 1.111 my $value = ERDB::TypeDefault($type);
3771 : parrello 1.6
3772 : parrello 1.111 Return the default value for fields of the specified type.
3773 : parrello 1.6
3774 :     =over 4
3775 :    
3776 : parrello 1.111 =item type
3777 : parrello 1.6
3778 : parrello 1.111 Relevant type name.
3779 : parrello 1.6
3780 :     =item RETURN
3781 :    
3782 : parrello 1.111 Returns a default value suitable for fields of the specified type.
3783 : parrello 1.6
3784 :     =back
3785 :    
3786 :     =cut
3787 :    
3788 : parrello 1.111 sub TypeDefault {
3789 : parrello 1.10 # Get the parameters.
3790 : parrello 1.111 my ($type) = @_;
3791 : parrello 1.115 # Validate the type.
3792 :     if (! exists $TypeTable->{$type}) {
3793 :     Confess("TypeDefault called for invalid type \"$type\".")
3794 :     }
3795 : parrello 1.10 # Return the result.
3796 : parrello 1.111 return $TypeTable->{$type}->default();
3797 : parrello 1.6 }
3798 :    
3799 : parrello 1.111 =head3 LoadTables
3800 : parrello 1.69
3801 : parrello 1.111 my $stats = $erdb->LoadTables($directoryName, $rebuild);
3802 : parrello 1.69
3803 : parrello 1.111 This method will load the database tables from a directory. The tables must
3804 :     already have been created in the database. (This can be done by calling
3805 :     L</CreateTables>.) The caller passes in a directory name; all of the relations
3806 :     to be loaded must have a file in the directory with the same name as the
3807 :     relation with a suffix of C<.dtx>. Each file must be a tab-delimited table of
3808 :     encoded field values. Each line of the file will be loaded as a row of the
3809 :     target relation table.
3810 : parrello 1.69
3811 :     =over 4
3812 :    
3813 : parrello 1.111 =item directoryName
3814 : parrello 1.69
3815 : parrello 1.111 Name of the directory containing the relation files to be loaded.
3816 : parrello 1.69
3817 : parrello 1.111 =item rebuild
3818 : parrello 1.69
3819 : parrello 1.111 TRUE if the tables should be dropped and rebuilt, else FALSE.
3820 : parrello 1.69
3821 :     =item RETURN
3822 :    
3823 : parrello 1.123 Returns a L</Stats> object describing the number of records read and a list of
3824 : parrello 1.111 the error messages.
3825 : parrello 1.69
3826 :     =back
3827 :    
3828 :     =cut
3829 :    
3830 : parrello 1.111 sub LoadTables {
3831 : parrello 1.69 # Get the parameters.
3832 : parrello 1.111 my ($self, $directoryName, $rebuild) = @_;
3833 :     # Start the timer.
3834 :     my $startTime = gettimeofday;
3835 :     # Clean any trailing slash from the directory name.
3836 :     $directoryName =~ s!/\\$!!;
3837 : parrello 1.69 # Declare the return variable.
3838 : parrello 1.111 my $retVal = Stats->new();
3839 :     # Get the relation names.
3840 :     my @relNames = $self->GetTableNames();
3841 :     for my $relationName (@relNames) {
3842 :     # Try to load this relation.
3843 :     my $result = $self->_LoadRelation($directoryName, $relationName,
3844 :     $rebuild);
3845 :     # Accumulate the statistics.
3846 :     $retVal->Accumulate($result);
3847 : parrello 1.69 }
3848 : parrello 1.111 # Add the duration of the load to the statistical object.
3849 :     $retVal->Add('duration', gettimeofday - $startTime);
3850 :     # Return the accumulated statistics.
3851 :     return $retVal;
3852 : parrello 1.69 }
3853 :    
3854 : parrello 1.111 =head3 CreateTables
3855 : parrello 1.6
3856 : parrello 1.111 $erdb->CreateTables();
3857 : parrello 1.6
3858 : parrello 1.111 This method creates the tables for the database from the metadata structure
3859 :     loaded by the constructor. It is expected this function will only be used on
3860 :     rare occasions, when the user needs to start with an empty database. Otherwise,
3861 :     the L</LoadTables> method can be used by itself with the truncate flag turned
3862 :     on.
3863 : parrello 1.6
3864 : parrello 1.111 =cut
3865 : parrello 1.6
3866 : parrello 1.111 sub CreateTables {
3867 :     # Get the parameters.
3868 :     my ($self) = @_;
3869 :     # Get the relation names.
3870 :     my @relNames = $self->GetTableNames();
3871 :     # Loop through the relations.
3872 :     for my $relationName (@relNames) {
3873 :     # Create a table for this relation.
3874 :     $self->CreateTable($relationName, 1);
3875 :     Trace("Relation $relationName created.") if T(2);
3876 :     }
3877 :     }
3878 : parrello 1.6
3879 : parrello 1.111 =head3 CreateTable
3880 : parrello 1.6
3881 : parrello 1.111 $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
3882 : parrello 1.6
3883 : parrello 1.111 Create the table for a relation and optionally create its indexes.
3884 : parrello 1.6
3885 : parrello 1.111 =over 4
3886 : parrello 1.6
3887 : parrello 1.111 =item relationName
3888 : parrello 1.6
3889 : parrello 1.111 Name of the relation (which will also be the table name).
3890 : parrello 1.6
3891 : parrello 1.111 =item indexFlag
3892 :    
3893 :     TRUE if the indexes for the relation should be created, else FALSE. If FALSE,
3894 :     L</CreateIndexes> must be called later to bring the indexes into existence.
3895 :    
3896 :     =item estimatedRows (optional)
3897 :    
3898 :     If specified, the estimated maximum number of rows for the relation. This
3899 :     information allows the creation of tables using storage engines that are
3900 :     faster but require size estimates, such as MyISAM.
3901 : parrello 1.6
3902 :     =back
3903 :    
3904 :     =cut
3905 :    
3906 : parrello 1.111 sub CreateTable {
3907 : parrello 1.10 # Get the parameters.
3908 : parrello 1.111 my ($self, $relationName, $indexFlag, $estimatedRows) = @_;
3909 :     # Get the database handle.
3910 :     my $dbh = $self->{_dbh};
3911 : parrello 1.166 # Determine whether or not the relation is primary.
3912 : parrello 1.111 my $rootFlag = $self->_IsPrimary($relationName);
3913 :     # Create a list of the field data.
3914 : parrello 1.166 my $fieldThing = $self->ComputeFieldString($relationName);
3915 : parrello 1.111 # Insure the table is not already there.
3916 : parrello 1.142 $dbh->drop_table(tbl => $self->{_quote} . $relationName . $self->{_quote});
3917 : parrello 1.111 Trace("Table $relationName dropped.") if T(2);
3918 : parrello 1.146 # Create an estimate of the table size.
3919 :     my $estimation;
3920 :     if ($estimatedRows) {
3921 :     $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
3922 :     Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
3923 :     }
3924 : parrello 1.111 # Create the table.
3925 :     Trace("Creating table $relationName: $fieldThing") if T(2);
3926 : parrello 1.142 $dbh->create_table(tbl => $self->{_quote} . $relationName . $self->{_quote}, flds => $fieldThing,
3927 : parrello 1.111 estimates => $estimation);
3928 :     Trace("Relation $relationName created in database.") if T(2);
3929 :     # If we want to build the indexes, we do it here. Note that the full-text
3930 :     # search index will not be built until the table has been loaded.
3931 :     if ($indexFlag) {
3932 :     $self->CreateIndex($relationName);
3933 : parrello 1.10 }
3934 : parrello 1.6 }
3935 : parrello 1.1
3936 : parrello 1.166 =head3 ComputeFieldString
3937 :    
3938 :     my $fieldString = $erdb->ComputeFieldString($relationName);
3939 :    
3940 :     Return the comma-delimited field definition string for a relation. This can be plugged directly into an SQL
3941 :     C<CREATE> statement.
3942 :    
3943 :     =over 4
3944 :    
3945 :     =item relationName
3946 :    
3947 :     Name of the relation whose field definition string is desired.
3948 :    
3949 :     =item RETURN
3950 :    
3951 :     Returns a string listing SQL field definitions, in the proper order, separated by commas.
3952 :    
3953 :     =back
3954 :    
3955 :     =cut
3956 :    
3957 :     sub ComputeFieldString {
3958 :     # Get the parameters.
3959 :     my ($self, $relationName) = @_;
3960 :     # Get the relation data.
3961 :     my $relationData = $self->FindRelation($relationName);
3962 :     # Create a list of the field data.
3963 :     my @fieldList;
3964 :     for my $fieldData (@{$relationData->{Fields}}) {
3965 :     # Assemble the field name and type.
3966 :     my $fieldString = $self->_FieldString($fieldData);
3967 :     # Push the result into the field list.
3968 :     push @fieldList, $fieldString;
3969 :     }
3970 :     # Convert the field list into a comma-delimited string.
3971 :     my $retVal = join(', ', @fieldList);
3972 :     return $retVal;
3973 :     }
3974 :    
3975 : parrello 1.111 =head3 VerifyFields
3976 :    
3977 :     $erdb->VerifyFields($relName, \@fieldList);
3978 : parrello 1.7
3979 : parrello 1.111 Run through the list of proposed field values, insuring that all of them are
3980 :     valid.
3981 : parrello 1.7
3982 : parrello 1.111 =over 4
3983 : parrello 1.7
3984 : parrello 1.111 =item relName
3985 : parrello 1.7
3986 : parrello 1.111 Name of the relation for which the specified fields are destined.
3987 : parrello 1.7
3988 : parrello 1.111 =item fieldList
3989 : parrello 1.7
3990 : parrello 1.111 Reference to a list, in order, of the fields to be put into the relation.
3991 : parrello 1.7
3992 : parrello 1.111 =back
3993 : parrello 1.7
3994 : parrello 1.111 =cut
3995 : parrello 1.7
3996 : parrello 1.111 sub VerifyFields {
3997 :     # Get the parameters.
3998 :     my ($self, $relName, $fieldList) = @_;
3999 :     # Initialize the return value.
4000 :     my $retVal = 0;
4001 :     # Get the relation definition.
4002 :     my $relData = $self->FindRelation($relName);
4003 :     # Get the list of field descriptors.
4004 :     my $fieldThings = $relData->{Fields};
4005 :     my $fieldCount = scalar @{$fieldThings};
4006 :     # Loop through the two lists.
4007 :     for (my $i = 0; $i < $fieldCount; $i++) {
4008 :     # Get the descriptor and type of the current field.
4009 :     my $fieldThing = $fieldThings->[$i];
4010 :     my $fieldType = $TypeTable->{$fieldThing->{type}};
4011 : parrello 1.131 Confess("Undefined field type $fieldThing->{type} in position $i ($fieldThing->{name}) of $relName.") if (! defined $fieldType);
4012 : parrello 1.111 # Validate it.
4013 :     my $message = $fieldType->validate($fieldList->[$i]);
4014 :     if ($message) {
4015 :     # It's invalid. Generate an error.
4016 :     Confess("Error in field $i ($fieldThing->{name}) of $relName: $message");
4017 :     }
4018 :     }
4019 :     # Return a 0 value, for backward compatibility.
4020 :     return 0;
4021 :     }
4022 : parrello 1.7
4023 : parrello 1.111 =head3 DigestFields
4024 : parrello 1.7
4025 : parrello 1.111 $erdb->DigestFields($relName, $fieldList);
4026 : parrello 1.7
4027 : parrello 1.111 Prepare the fields of a relation for output to a load file.
4028 : parrello 1.7
4029 : parrello 1.111 =over 4
4030 : parrello 1.7
4031 : parrello 1.111 =item relName
4032 : parrello 1.7
4033 : parrello 1.111 Name of the relation to which the fields belong.
4034 : parrello 1.7
4035 : parrello 1.111 =item fieldList
4036 : parrello 1.7
4037 : parrello 1.111 List of field contents to be loaded into the relation.
4038 : parrello 1.7
4039 :     =back
4040 :    
4041 :     =cut
4042 : parrello 1.111 #: Return Type ;
4043 :     sub DigestFields {
4044 : parrello 1.10 # Get the parameters.
4045 : parrello 1.111 my ($self, $relName, $fieldList) = @_;
4046 :     # Get the relation definition.
4047 :     my $relData = $self->FindRelation($relName);
4048 :     # Get the list of field descriptors.
4049 :     my $fieldTypes = $relData->{Fields};
4050 :     my $fieldCount = scalar @{$fieldTypes};
4051 :     # Loop through the two lists.
4052 :     for (my $i = 0; $i < $fieldCount; $i++) {
4053 :     # Get the type of the current field.
4054 :     my $fieldType = $fieldTypes->[$i]->{type};
4055 :     # Encode the field value in place.
4056 :     $fieldList->[$i] = $TypeTable->{$fieldType}->encode($fieldList->[$i], 1);
4057 : parrello 1.30 }
4058 : parrello 1.7 }
4059 :    
4060 : parrello 1.111 =head3 EncodeField
4061 : parrello 1.55
4062 : parrello 1.111 my $coding = $erdb->EncodeField($fieldName, $value);
4063 : parrello 1.55
4064 : parrello 1.111 Convert the specified value to the proper format for storing in the
4065 :     specified database field. The field name should be specified in the
4066 :     standard I<object(field)> format, e.g. C<Feature(id)> for the C<id> field
4067 :     of the C<Feature> table.
4068 : parrello 1.55
4069 :     =over 4
4070 :    
4071 : parrello 1.111 =item fieldName
4072 : parrello 1.55
4073 : parrello 1.111 Name of the field, specified in as an object name with the field name
4074 :     in parentheses.
4075 : parrello 1.55
4076 : parrello 1.111 =item value
4077 : parrello 1.55
4078 : parrello 1.111 Value to encode for placement in the field.
4079 : parrello 1.55
4080 :     =item RETURN
4081 :    
4082 : parrello 1.111 Coded value ready to put in the database. In most cases, this will be
4083 :     identical to the original input.
4084 : parrello 1.55
4085 :     =back
4086 :    
4087 :     =cut
4088 : parrello 1.111
4089 :     sub EncodeField {
4090 : parrello 1.55 # Get the parameters.
4091 : parrello 1.111 my ($self, $fieldName, $value) = @_;
4092 :     # Find the field type.
4093 :     my $fieldSpec = $self->_FindField($fieldName);
4094 :     my $retVal = encode($fieldSpec->{type}, $value);
4095 :     # Return the result.
4096 : parrello 1.55 return $retVal;
4097 :     }
4098 :    
4099 : parrello 1.111 =head3 encode
4100 : parrello 1.18
4101 : parrello 1.111 my $coding = ERDB::encode($type, $value);
4102 : parrello 1.18
4103 : parrello 1.111 Encode a value of the specified type for storage in the database or for
4104 :     use as a query parameter. Encoding is automatic for all ERDB methods except
4105 :     when loading a table from a user-supplied load file or when processing
4106 :     the parameters for a query filter string. This method can be used in
4107 :     those situations to remedy the lack.
4108 : parrello 1.18
4109 :     =over 4
4110 :    
4111 : parrello 1.111 =item type
4112 :    
4113 :     Name of the incoming value's data type.
4114 :    
4115 :     =item value
4116 : parrello 1.18
4117 : parrello 1.111 Value to encode into a string.
4118 : parrello 1.18
4119 :     =item RETURN
4120 :    
4121 : parrello 1.111 Returns the encoded value.
4122 : parrello 1.18
4123 :     =back
4124 :    
4125 :     =cut
4126 : parrello 1.111
4127 :     sub encode {
4128 : parrello 1.18 # Get the parameters.
4129 : parrello 1.111 my ($type, $value) = @_;
4130 :     # Get the type definition.
4131 :     my $typeData = $TypeTable->{$type};
4132 :     # Complain if it doesn't exist.
4133 :     Confess("Invalid data type \"$type\" specified in encoding.") if ! defined $typeData;
4134 :     # Encode the value.
4135 :     my $retVal = $typeData->encode($value);
4136 : parrello 1.18 # Return the result.
4137 :     return $retVal;
4138 :     }
4139 :    
4140 : parrello 1.111 =head3 DecodeField
4141 : parrello 1.38
4142 : parrello 1.111 my $value = $erdb->DecodeField($fieldName, $coding);
4143 : parrello 1.38
4144 : parrello 1.111 Convert the stored coding of the specified field to the proper format for
4145 :     use by the client program. This is essentially the inverse of
4146 :     L</EncodeField>.
4147 : parrello 1.38
4148 :     =over 4
4149 :    
4150 : parrello 1.111 =item fieldName
4151 :