Object/Metadata/Auto/Informix.pm untested

filter: Statementstmt 0.0% 0 / 365 Branchbran 0.0% 0 / 82 Conditioncond 0.0% 0 / 105 MC/DCmcdc 0.0% 0 / 59 Subroutinesub 0.0% 0 / 51 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 670 CC 42 SCAR 40.3
CC
42
Cov
0%
auto_generate_columns
210.0
auto_generate_foreign_keys
132.0
_ix_datetime_specific_type
56.0
CRAP 56.1
1 package Rose::DB::Object::Metadata::Auto::Informix;
2  
3 use strict;
4  
5 use Carp();
6  
7 use Rose::DB::Object::Metadata::ForeignKey;
8 use Rose::DB::Object::Metadata::UniqueKey;
9  
10 use Rose::DB::Object::Metadata::Auto;
11 our @ISA = qw(Rose::DB::Object::Metadata::Auto);
12  
13 our $VERSION = '0.784';
14  
15 # syscolumns.coltype constants taken from:
16 #
17 # http://www-306.ibm.com/software/data/informix/pubs/library/datablade/dbdk/sqlr/01.fm14.html
18 use constant CHAR => 0;
19 use constant SMALLINT => 1;
20 use constant INTEGER => 2;
21 use constant FLOAT => 3;
22 use constant SMALLFLOAT => 4;
23 use constant DECIMAL => 5;
24 use constant SERIAL => 6;
25 use constant DATE => 7;
26 use constant MONEY => 8;
27 use constant NULL => 9;
28 use constant DATETIME => 10;
29 use constant BYTE => 11;
30 use constant TEXT => 12;
31 use constant VARCHAR => 13;
32 use constant INTERVAL => 14;
33 use constant NCHAR => 15;
34 use constant NVARCHAR => 16;
35 use constant INT8 => 17;
36 use constant SERIAL8 => 18;
37 use constant SET => 19;
38 use constant MULTISET => 20;
39 use constant LIST => 21;
40 use constant ROW => 22;
41 use constant COLLECTION => 23;
42 use constant ROWREF => 24;
43  
44 use constant VARIABLE_LENGTH_OPAQUE => 40; # Variable-length opaque type
45 use constant FIXED_LENGTH_OPAQUE => 41; # Fixed-length opaque type
46 use constant NAMED_ROW_TYPE => 4118; # Named row type
47  
48 # Map the Informix column type constants to type names that we can
49 # handle--or that are at least in our format: lowercase text.
50 my %Column_Types =
51 (
52 CHAR() => 'char',
53 SMALLINT() => 'int',
54 INTEGER() => 'int',
55 FLOAT() => 'float',
56 SMALLFLOAT() => 'float',
57 DECIMAL() => 'decimal',
58 SERIAL() => 'serial',
59 DATE() => 'date',
60 MONEY() => 'decimal',
61 NULL() => 'null',
62 DATETIME() => 'datetime',
63 BYTE() => 'byte',
64 TEXT() => 'text',
65 VARCHAR() => 'varchar',
66 INTERVAL() => 'interval',
67 NCHAR() => 'char',
68 NVARCHAR() => 'varchar',
69 INT8() => 'int',
70 SERIAL8() => 'bigserial',
71 SET() => 'set',
72 MULTISET() => 'multiset',
73 LIST() => 'list',
74 ROW() => 'row',
75 COLLECTION() => 'collection',
76 ROWREF() => 'rowref',
77 );
78  
79 # http://www-306.ibm.com/software/data/informix/pubs/library/datablade/dbdk/sqlr/01.fm14.html
80 my %Column_Length =
81 (
82 # Data Type Length (in bytes)
83 SMALLINT() => 2,
84 INTEGER() => 4,
85 INT8() => 8,
86 );
87  
88 # http://www-306.ibm.com/software/data/informix/pubs/library/datablade/dbdk/sqlr/01.fm14.html
89 my %Datetime_Qualifiers =
90 (
91 0 => 'year',
92 2 => 'month',
93 4 => 'day',
94 6 => 'hour',
95 8 => 'minute',
96 10 => 'second',
97 11 => 'fraction(1)',
98 12 => 'fraction(2)',
99 13 => 'fraction(3)',
100 14 => 'fraction(4)',
101 15 => 'fraction(5)',
102 );
103  
104 my %Datetime_Qualifiers_Reverse = (reverse %Datetime_Qualifiers);
105  
106 # Value minus this delta = scale for fraction(n) types
107 use constant FRACTION_SCALE_DELTA => 10;
108  
109 use constant MIN_DATETIME_FRACTION => 11; # fraction(1)
110 use constant MAX_DATETIME_FRACTION => 15; # fraction(5)
111  
112 # $INFORMIXDIR/etc/xpg4_is.sql
113 # http://www-306.ibm.com/software/data/informix/pubs/library/datablade/dbdk/sqlr/01.fm50.html
114 my %Numeric_Precision =
115 (
116 SMALLINT() => 5,
117 INTEGER() => 10,
118 FLOAT() => 63,
119 SMALLFLOAT() => 32,
120 );
121  
122 # These constants are from the DBI documentation. Is there somewhere
123 # I can load these from?
124 use constant SQL_NO_NULLS => 0;
125 use constant SQL_NULLABLE => 1;
126  
127 sub auto_generate_columns
128 {
129 my($self) = shift;
130  
131 my($class, %columns, $table_id, $error);
132  
133 TRY:
134 {
135 local $@;
136  
137 eval
138 {
139 require DBD::Informix::Metadata;
140  
141 $class = $self->class or die "Missing class!";
142  
143 my $db = $self->db;
144 my $dbh = $db->dbh or die $db->error;
145  
146 local $dbh->{'FetchHashKeyName'} = 'NAME';
147  
148 # Informix does not support DBI's column_info() method so we have
149 # to get all that into "the hard way."
150 #
151 # Each item in @col_list is a reference to an array of values:
152 #
153 # 0 owner name
154 # 1 table name
155 # 2 column number
156 # 3 column name
157 # 4 data type (encoded)
158 # 5 data length (encoded)
159 #
160 # Lowercase table because Rose::DB::Informix->likes_lowercase_table_names
161 my @col_list = DBD::Informix::Metadata::ix_columns($dbh, lc $self->table);
162  
163 # We'll also need to query the syscolumns table directly to get the
164 # table id, which we need to query the sysdefaults table. But to get
165 # the correct syscolumns record, we need to first query the systables
166 # table.
167 my $st_sth = $dbh->prepare(<<"EOF");
168 SELECT tabid FROM informix.systables WHERE tabname = ? AND owner = ?
169 EOF
170  
171 my %col_info;
172  
173 foreach my $item (@col_list)
174 {
175 # We're going to build a standard DBI column_info() data structure
176 # to pass on to the rest of the code.
177 my $col_info;
178  
179 # Add the "proprietary" values using the DBI convention of lowercase
180 # names prefixed with DBD name.
181 my @keys = map { "informix_$_" }
182 qw(owner table column_number column_name column_type column_length);
183  
184 @$col_info{@keys} = @$item;
185  
186 # Copy the "easy" values into the standard DBI locations
187 $col_info->{'TABLE_NAME'} = $col_info->{'informix_table'};
188 $col_info->{'COLUMN_NAME'} = $col_info->{'informix_column_name'};
189  
190 # Query the systables table to get the table id based on the
191 # table name and owner name.
192 $st_sth->execute(@$col_info{qw(informix_table informix_owner)});
193  
194 $table_id = $st_sth->fetchrow_array;
195  
196 unless(defined $table_id)
197 {
198 die "Could not find informix.systables record for table '",
199 $col_info->{'informix_table'}, "' with owner '",
200 $col_info->{'informix_owner'}, "'";
201 }
202  
203 $col_info->{'informix_tabid'} = $table_id;
204  
205 # Store the column info by column name
206 $col_info{$col_info->{'COLUMN_NAME'}} = $col_info;
207 }
208  
209 # We need to query the syscolumns table directly to get the
210 # table id, which we need to query the sysdefaults table.
211 my $sc_sth = $dbh->prepare(<<"EOF");
212 SELECT * FROM informix.syscolumns WHERE tabid = ?
213 EOF
214  
215 # We may need to query the sysxtdtypes table, so reserve a
216 # variable for that statement handle. We'll also cache the
217 # results, so we'll set up that hash here too. We'll also
218 # need a mapping from "colno" to column name.
219 my($sxt_sth, %extended_type, %colno_to_name);
220  
221 # Query the syscolumns table to get some more column information
222 $sc_sth->execute($table_id);
223  
224 while(my $sc_row = $sc_sth->fetchrow_hashref)
225 {
226 my $col_info = $col_info{$sc_row->{'colname'}}
227 or die "No column info found for column name '$sc_sth->{'colname'}'";
228  
229 # Copy all the row values into the DBI column info using the DBI
230 # convention of lowercase names prefixed with DBD name.
231 @$col_info{map { "informix_$_" } keys %$sc_row} = values %$sc_row;
232  
233 # Store mapping from "colno" to column name
234 $colno_to_name{$sc_row->{'colno'}} = $sc_row->{'colname'};
235  
236 ##
237 ## Painfully derive the data type name (TYPE_NAME)
238 ##
239  
240 # If the coltype is a value greater than or equal to 256, the
241 # column does not allow null values. To determine the data type for
242 # a coltype column that contains a value greater than 256, subtract
243 # 256 from the value and evaluate the remainder, based on the
244 # possible coltype values. For example, if a column has a coltype
245 # value of 262, subtracting 256 from 262 leaves a remainder of 6,
246 # which indicates that this column uses a SERIAL data type.
247  
248 my $type_num;
249  
250 if($sc_row->{'coltype'} >= 256)
251 {
252 $col_info->{'informix_type_num'} = $type_num =
253 $sc_row->{'coltype'} - 256;
254  
255 # This situation also indicates that the column is NOT NULL,
256 # so set all the DBI-style attributes to indicate that.
257 $col_info->{'IS_NULLABLE'} = 'NO';
258 $col_info->{'NULLABLE'} = SQL_NO_NULLS;
259 }
260 else
261 {
262 $col_info->{'informix_type_num'} = $type_num = $sc_row->{'coltype'};
263  
264 $col_info->{'IS_NULLABLE'} = 'YES';
265 $col_info->{'NULLABLE'} = SQL_NULLABLE;
266 }
267  
268 #
269 # Now we need to turn $type_num into a type name. Hold on to your hat.
270 #
271  
272 my $type_name;
273  
274 # The following data types are implemented by the database server
275 # as built-in opaque types: BLOB, BOOLEAN, CLOB, and LVARCHAR
276 #
277 # A built-in opaque data type is one for which the database server
278 # provides the type definition. Because these data types are built-in
279 # opaque types, they do not have a unique coltype value. Instead, they
280 # have one of the coltype values for opaque types: 41 (fixed-length
281 # opaque type), or 40 (varying-length opaque type). The different
282 # fixed-length opaque types are distinguished by the extended_id column
283 # in the sysxtdtypes system catalog table.
284 #
285 # The following table summarizes the coltype values for the predefined
286 # data types.
287 #
288 # Type coltype symbolic constant
289 # -------- ------- -----------------
290 # BLOB 41 FIXED_LENGTH_OPAQUE
291 # CLOB 41 FIXED_LENGTH_OPAQUE
292 # BOOLEAN 41 FIXED_LENGTH_OPAQUE
293 # LVARCHAR 40 VARIABLE_LENGTH_OPAQUE
294  
295 # BLOB, CLOB, or BOOLEAN
296 if($type_num == FIXED_LENGTH_OPAQUE)
297 {
298 # Maybe we already looked this one up
299 if($extended_type{$sc_row->{'extended_id'}})
300 {
301 $type_name = $extended_type{$col_info->{'informix_extended_id'}};
302 }
303 else # look it up and cache it
304 {
305 $sxt_sth ||=
306 $dbh->prepare("SELECT name FROM informix.sysxtdtypes WHERE extended_id = ?");
307  
308 $sxt_sth->execute($sc_row->{'extended_id'});
309  
310 my $name = $sxt_sth->fetchrow_array;
311  
312 # We only handle BOOLEANS specially, and the name column for
313 # booleans is already in our type name format: "boolean"
314 # So just copy the name value into the cache.
315 $type_name = $extended_type{$sc_row->{'extended_id'}} = $name;
316 }
317 }
318 elsif($type_num == VARIABLE_LENGTH_OPAQUE) # LVARCHAR
319 {
320 $type_name = 'varchar';
321 }
322 elsif($type_num == DATETIME)
323 {
324 # Determine the full "datetime X to Y" type string
325 $type_name = _ix_datetime_specific_type($self, $type_num, $sc_row->{'collength'}, $col_info);
326 }
327 else
328 {
329 $type_name = $Column_Types{$type_num};
330 }
331  
332 # Finally, set the type name
333 $col_info->{'TYPE_NAME'} = $type_name;
334  
335 #
336 # Mine column length for information
337 #
338  
339 # COLUMN_SIZE is the maximum length in characters for character data
340 # types, the number of digits or bits for numeric data types or the
341 # length in the representation of temporal types. See the relevant
342 # specifications for detailed information.
343  
344 $col_info->{'COLUMN_SIZE'} =
345 _ix_max_length($type_num, $sc_row->{'collength'});
346  
347 if($type_num == SMALLINT || $type_num == INTEGER ||
348 $type_num == SERIAL || $type_num == DECIMAL ||
349 $type_num == MONEY)
350 {
351 $col_info->{'DECIMAL_DIGITS'} =
352 _ix_numeric_scale($type_num, $sc_row->{'collength'});
353  
354 $col_info->{'COLUMN_SIZE'} =
355 _ix_numeric_precision($type_num, $sc_row->{'collength'});
356  
357 $col_info->{'NUM_PREC_RADIX'} =
358 _ix_numeric_precision_radix($type_num, $sc_row->{'collength'});
359 }
360 }
361  
362 #
363 # Get all the column default values from the sysdefaults table
364 #
365  
366 # class 'T' means "table" (the other possible value us "t" for "row type")
367 # http://www-306.ibm.com/software/data/informix/pubs/library/datablade/dbdk/sqlr/01.fm16.html
368 my $sd_sth = $dbh->prepare(<<"EOF");
369 SELECT * FROM informix.sysdefaults WHERE tabid = ? AND class = 'T'
370 EOF
371  
372 $sd_sth->execute($table_id);
373  
374 while(my $sd_row = $sd_sth->fetchrow_hashref)
375 {
376 my $col_name = $colno_to_name{$sd_row->{'colno'}}
377 or die "While getting defaults: no column name found for colno '$sd_row->{'colno'}'";
378  
379 my $col_info = $col_info{$col_name}
380 or die "While getting defaults: no column info found for column '$col_name'";
381  
382 # The "type" column of the sysdefaults table looks like this:
383 #
384 # type CHAR(1)
385 #
386 # 'L' = Literal default
387 # 'U' = User
388 # 'C' = Current
389 # 'N' = Null
390 # 'T' = Today
391 # 'S' = Dbservername
392 #
393 # If a literal is specified for the default value, it is stored in
394 # the default column as text. If the literal value is not of type
395 # CHAR, the default column consists of two parts. The first part is
396 # the 6-bit representation of the binary value of the default-value
397 # structure. The second part is the default value in English text.
398 # The two parts are separated by a space.
399 #
400 # If the data type of the column is not CHAR or VARCHAR, a binary
401 # representation is encoded in the default column.
402  
403 if($sd_row->{'type'} eq 'T')
404 {
405 $col_info->{'COLUMN_DEF'} = 'today';
406 }
407 elsif($sd_row->{'type'} eq 'C')
408 {
409 $col_info->{'COLUMN_DEF'} = 'current';
410 }
411 elsif($sd_row->{'type'} eq 'L')
412 {
413 if($col_info->{'informix_type_num'} == CHAR)
414 {
415 $col_info->{'COLUMN_DEF'} = $sd_row->{'default'};
416 }
417 else
418 {
419 # The first part is the 6-bit representation of the binary value
420 # of the default-value structure. The second part is the default
421 # value in English text. The two parts are separated by a space.
422 my $default = $sd_row->{'default'};
423 $default =~ s/^.+ //; # cheat by just looking for the space
424  
425 $col_info->{'COLUMN_DEF'} = $default;
426 }
427 }
428 }
429  
430 # Finally, generate the columns based on the DBI-like $col_info
431 # that we built in the previous steps.
432  
433 foreach my $col_info (values %col_info)
434 {
435 $db->refine_dbi_column_info($col_info);
436  
437 $columns{$col_info->{'COLUMN_NAME'}} =
438 $self->auto_generate_column($col_info->{'COLUMN_NAME'}, $col_info);
439 }
440 };
441  
442 $error = $@;
443 }
444  
445 if($error || !keys %columns)
446 {
447 Carp::croak "Could not auto-generate columns for class $class - $error";
448 }
449  
450 $self->auto_alias_columns(values %columns);
451  
452 return wantarray ? values %columns : \%columns;
453 }
454  
455 sub auto_generate_unique_keys
456 {
457 my($self) = shift;
458  
459 unless(defined wantarray)
460 {
461 Carp::croak "Useless call to auto_generate_unique_keys() in void context";
462 }
463  
464 my($class, %unique_keys, $error);
465  
466 TRY:
467 {
468 local $@;
469  
470 eval
471 {
472 require DBD::Informix::Metadata;
473  
474 $class = $self->class or die "Missing class!";
475  
476 my $db = $self->db;
477 my $dbh = $db->dbh or die $db->error;
478  
479 local $dbh->{'FetchHashKeyName'} = 'NAME';
480  
481 # We need the table id. To get it, we need the "owner" name. Asking
482 # for column information is the only way I know of to reliably get
483 # this information.
484 #
485 # Informix does not support DBI's column_info() method so we have
486 # to get all that into "the hard way."
487 #
488 # Each item in @col_list is a reference to an array of values:
489 #
490 # 0 owner name
491 # 1 table name
492 # 2 column number
493 # 3 column name
494 # 4 data type (encoded)
495 # 5 data length (encoded)
496 #
497 my @col_list = DBD::Informix::Metadata::ix_columns($dbh, lc $self->table);
498  
499 # Here's the query for the table id
500 my $st_sth = $dbh->prepare(<<"EOF");
501 SELECT tabid FROM informix.systables WHERE tabname = ? AND owner = ?
502 EOF
503  
504 # Take the info from the first column (arbitrarily selected)
505 # table name owner name
506 $st_sth->execute($col_list[0][1], $col_list[0][0]);
507 my $table_id = $st_sth->fetchrow_array;
508  
509 unless(defined $table_id)
510 {
511 die "Could not find informix.systables record for table ",
512 "'$col_list[0][1]' with owner '$col_list[0][0]'";
513 }
514  
515 # Then comes this monster query to get the unique key column names.
516 # (The subquery filters out any primary keys.) I'd love to know a
517 # better/easier way to do this...
518 my $uk_sth = $dbh->prepare(<<'EOF');
519 SELECT
520 col.colname,
521 idx.idxname
522 FROM
523 informix.sysindexes idx,
524 informix.syscolumns col
525 WHERE
526 idx.tabid = ? AND
527 idx.idxtype = 'U' AND
528 idx.tabid = col.tabid
529 AND
530 (
531 col.colno = idx.part1 OR
532 col.colno = idx.part2 OR
533 col.colno = idx.part3 OR
534 col.colno = idx.part4 OR
535 col.colno = idx.part5 OR
536 col.colno = idx.part6 OR
537 col.colno = idx.part7 OR
538 col.colno = idx.part8 OR
539 col.colno = idx.part9 OR
540 col.colno = idx.part10 OR
541 col.colno = idx.part11 OR
542 col.colno = idx.part12 OR
543 col.colno = idx.part13 OR
544 col.colno = idx.part14 OR
545 col.colno = idx.part15 OR
546 col.colno = idx.part16
547 )
548 AND NOT EXISTS
549 (
550 SELECT * FROM
551 informix.sysconstraints con
552 WHERE
553 con.tabid = ? AND
554 con.constrtype = 'P' AND
555 con.idxname = idx.idxname
556 );
557 EOF
558  
559 $uk_sth->execute($table_id, $table_id);
560  
561 my($column, $key);
562  
563 $uk_sth->bind_columns(\$column, \$key);
564  
565 while($uk_sth->fetch)
566 {
567 my $uk = $unique_keys{$key} ||=
568 Rose::DB::Object::Metadata::UniqueKey->new(name => $key, parent => $self);
569  
570 $uk->add_column($column);
571 }
572 };
573  
574 $error = $@;
575 }
576  
577 if($error)
578 {
579 Carp::croak "Could not auto-retrieve unique keys for class $class - $error";
580 }
581  
582 # This sort order is part of the API, and is essential to make the
583 # test suite work.
584 my @uk = map { $unique_keys{$_} } sort map { lc } keys(%unique_keys);
585  
586 return wantarray ? @uk : \@uk;
587 }
588  
589 use constant FK_INDEXES_SQL =><<'EOF';
590 SELECT
591 c1.constrname referring_constraint_name,
592 c1.owner referring_constraint_owner,
593 c1.idxname referring_index_name,
594 t2.tabid referring_table_id,
595 t2.owner referring_table_owner,
596 t2.tabname referring_table_name,
597 c2.constrname referred_constraint_name,
598 c2.owner referred_constraint_owner,
599 c2.idxname referred_index_name,
600 t1.tabid referred_table_id,
601 t1.owner referred_table_owner,
602 t1.tabname referred_table_name
603 FROM
604 informix.sysreferences r,
605 informix.sysconstraints c1,
606 informix.sysconstraints c2,
607 informix.systables t1,
608 informix.systables t2
609 WHERE
610 c1.constrtype = 'R' AND
611 c1.tabid = t2.tabid AND
612 c1.constrid = r.constrid AND
613 r.ptabid = t1.tabid AND
614 r.primary = c2.constrid AND
615 t2.tabid = ?
616 EOF
617  
618 use constant INDEX_COLUMNS_SQL =><<'EOF';
619 SELECT
620 tabname,
621 idxname,
622 c1.colname col1,
623 c2.colname col2,
624 c3.colname col3,
625 c4.colname col4,
626 c5.colname col5,
627 c6.colname col6,
628 c7.colname col7,
629 c8.colname col8,
630 c9.colname col9,
631 c10.colname col10,
632 c11.colname col11,
633 c12.colname col12,
634 c13.colname col13,
635 c14.colname col14,
636 c15.colname col15,
637 c16.colname col16
638 FROM
639 informix.systables t,
640 informix.syscolumns c1,
641 OUTER(informix.syscolumns c2),
642 OUTER(informix.syscolumns c3),
643 OUTER(informix.syscolumns c4),
644 OUTER(informix.syscolumns c5),
645 OUTER(informix.syscolumns c6),
646 OUTER(informix.syscolumns c7),
647 OUTER(informix.syscolumns c8),
648 OUTER(informix.syscolumns c9),
649 OUTER(informix.syscolumns c10),
650 OUTER(informix.syscolumns c11),
651 OUTER(informix.syscolumns c12),
652 OUTER(informix.syscolumns c13),
653 OUTER(informix.syscolumns c14),
654 OUTER(informix.syscolumns c15),
655 OUTER(informix.syscolumns c16),
656 informix.sysindexes i
657 WHERE
658 t.tabtype = 'T' AND
659 t.tabid = i.tabid AND
660 i.tabid = c1.tabid AND
661 i.tabid = c2.tabid AND
662 i.tabid = c3.tabid AND
663 i.tabid = c4.tabid AND
664 i.tabid = c5.tabid AND
665 i.tabid = c6.tabid AND
666 i.tabid = c7.tabid AND
667 i.tabid = c8.tabid AND
668 i.tabid = c9.tabid AND
669 i.tabid = c10.tabid AND
670 i.tabid = c11.tabid AND
671 i.tabid = c12.tabid AND
672 i.tabid = c13.tabid AND
673 i.tabid = c14.tabid AND
674 i.tabid = c15.tabid AND
675 i.tabid = c16.tabid AND
676 part1 = c1.colno AND
677 part2 = c2.colno AND
678 part3 = c3.colno AND
679 part4 = c4.colno AND
680 part5 = c5.colno AND
681 part6 = c6.colno AND
682 part7 = c7.colno AND
683 part8 = c8.colno AND
684 part9 = c9.colno AND
685 part10 = c10.colno AND
686 part11 = c11.colno AND
687 part12 = c12.colno AND
688 part13 = c13.colno AND
689 part14 = c14.colno AND
690 part15 = c15.colno AND
691 part16 = c16.colno AND
692 t.tabid = ? AND
693 i.idxname = ?
694 ORDER BY
695 idxname
696 EOF
697  
698 sub auto_generate_foreign_keys
699 {
700 my($self, %args) = @_;
701  
702 unless(defined wantarray)
703 {
704 Carp::croak "Useless call to auto_generate_foreign_keys() in void context";
705 }
706  
707 my $no_warnings = $args{'no_warnings'};
708  
709 my($class, @foreign_keys, $total_fks, $error);
710  
711 TRY:
712 {
713 local $@;
714  
715 eval
716 {
717 $class = $self->class or die "Missing class!";
718  
719 my $db = $self->db;
720 my $dbh = $db->dbh or die $db->error;
721  
722 local $dbh->{'FetchHashKeyName'} = 'NAME';
723  
724 # I'm doing this to get the table id and owner. Gotta be a better way...
725 my @col_list = DBD::Informix::Metadata::ix_columns($dbh, lc $self->table);
726  
727 my $st_sth = $dbh->prepare(<<"EOF");
728 SELECT tabid FROM informix.systables WHERE tabname = ? AND owner = ?
729 EOF
730 # Each item in @col_list is a reference to an array of values:
731 #
732 # 0 owner name
733 # 1 table name
734 # 2 column number
735 # 3 column name
736 # 4 data type (encoded)
737 # 5 data length (encoded)
738 #
739 my $table_name = $col_list[0][1];
740 my $owner_name = $col_list[0][0];
741  
742 $st_sth->execute($table_name, $owner_name);
743  
744 my $table_id = $st_sth->fetchrow_array;
745  
746 my $col_sth = $dbh->prepare(INDEX_COLUMNS_SQL);
747  
748 my $sth = $dbh->prepare(FK_INDEXES_SQL);
749 $sth->execute($table_id);
750  
751 my %fk;
752  
753 my $cm = $self->convention_manager;
754  
755 FK: while(my $index_info = $sth->fetchrow_hashref)
756 {
757 # Sanity check - should never happen
758 unless(lc $self->table eq lc $index_info->{'referring_table_name'} &&
759 lc $owner_name eq lc $index_info->{'referring_table_owner'})
760 {
761 Carp::confess
762 "Fatal mismatch between table ('", lc $self->table, "' vs. '",
763 lc $index_info->{'referring_table_name'}, "' and/or owner ('",
764 lc $owner_name, "' vs. '", lc $index_info->{'referring_table_owner'},
765 "')";
766 }
767  
768 my $key_name = $index_info->{'referring_index_name'};
769 my $foreign_table = $index_info->{'referred_table_name'};
770  
771 # Get local columns
772 $col_sth->execute(@$index_info{qw(referring_table_id referring_index_name)});
773  
774 my $local_cols_info = $col_sth->fetchrow_hashref;
775 my @local_cols = grep { defined && /\S/ } @$local_cols_info{map { "col$_" } 1 .. 16};
776  
777 # Get foreign columns
778 $col_sth->execute(@$index_info{qw(referred_table_id referred_index_name)});
779  
780 my $foreign_cols_info = $col_sth->fetchrow_hashref;
781 my @foreign_cols = grep { defined && /\S/ } @$foreign_cols_info{map { "col$_" } 1 .. 16};
782  
783 # Another sanity check - should never happen
784 unless(@local_cols > 0 && @local_cols == @foreign_cols)
785 {
786 Carp::confess "Failed to extract matching sets of foreign key ",
787 "columns for table $table_name";
788 }
789  
790 my $foreign_class = $self->class_for(table => $foreign_table);
791  
792 unless($foreign_class)
793 {
794 # Add deferred task
795 $self->add_deferred_task(
796 {
797 class => $self->class,
798 method => 'auto_init_foreign_keys',
799 args => \%args,
800  
801 code => sub
802 {
803 $self->auto_init_foreign_keys(%args);
804 $self->make_foreign_key_methods(%args, preserve_existing => 1);
805 },
806  
807 check => sub
808 {
809 my $fks = $self->foreign_keys;
810 return @$fks == $total_fks ? 1 : 0;
811 }
812 });
813  
814 unless($no_warnings || $self->allow_auto_initialization)
815 {
816 no warnings; # Allow undef coercion to empty string
817 warn "No Rose::DB::Object-derived class found for table ",
818 "'$foreign_table'";
819 }
820  
821 $total_fks++;
822 next FK;
823 }
824  
825 my %key_columns;
826 @key_columns{@local_cols} = @foreign_cols;
827  
828 my $fk =
829 Rose::DB::Object::Metadata::ForeignKey->new(
830 name => $key_name,
831 class => $foreign_class,
832 key_columns => \%key_columns);
833  
834 push(@foreign_keys, $fk);
835 $total_fks++;
836 }
837  
838 # This step is important! It ensures that foreign keys will be created
839 # in a deterministic order, which in turn allows the "auto-naming" of
840 # foreign keys to work in a predictable manner. This exact sort order
841 # (lowercase table name comparisons) is part of the API for foreign
842 # key auto generation.
843 @foreign_keys =
844 sort { lc $a->class->meta->table cmp lc $b->class->meta->table }
845 @foreign_keys;
846  
847 my %used_names;
848  
849 foreach my $fk (@foreign_keys)
850 {
851 my $name =
852 $cm->auto_foreign_key_name($fk->class, $fk->name, scalar $fk->key_columns, \%used_names);
853  
854 unless(defined $name)
855 {
856 $fk->name($name = $self->foreign_key_name_generator->($self, $fk));
857 }
858  
859 unless(defined $name && $name =~ /^\w+$/)
860 {
861 die "Missing or invalid key name '$name' for foreign key ",
862 "generated in $class for ", $fk->class;
863 }
864  
865 $used_names{$name}++;
866  
867 $fk->name($name);
868 }
869 };
870  
871 $error = $@;
872 }
873  
874 if($error)
875 {
876 Carp::croak "Could not auto-generate foreign keys for class $class - $error";
877 }
878  
879 @foreign_keys = sort { lc $a->name cmp lc $b->name } @foreign_keys;
880  
881 return wantarray ? @foreign_keys : \@foreign_keys;
882 }
883  
884 #
885 # Crazy Informix helper functions
886 #
887  
888 # Helper functions from $INFORMIXDIR/etc/xpg4_is.sql
889 # http://www-306.ibm.com/software/data/informix/pubs/library/datablade/dbdk/sqlr/01.fm50.html
890 #
891 # In call cases, the "coltype" argument is replaces with the already-
892 # adjusted $type_num, so ignore the subtraction of 256 in all of the
893 # pasted code.
894  
895 # create procedure 'informix'.ansinumprec(coltype smallint, collength smallint)
896 # returning int;
897 #
898 # { FLOAT and SMALLFLOAT precisions are in bits }
899 #
900 # if (coltype >= 256) then
901 # let coltype = coltype - 256;
902 # end if;
903 #
904 # if (coltype = 1) then -- smallint
905 # return 5;
906 # elif (coltype = 2) or (coltype = 6) then -- int
907 # return 10;
908 # elif (coltype = 3) then -- float
909 # return 64;
910 # elif (coltype = 4) then -- smallfloat
911 # return 32;
912 # elif (coltype = 5) or (coltype = 8) then -- decimal
913 # return (trunc(collength / 256));
914 # else
915 # return NULL;
916 # end if;
917 # end procedure
918 # document
919 # 'returns the precision of a numeric column',
920 # 'Synopsis: ansinumprec(smallint, smallint) returns int';
921  
922 sub _ix_numeric_precision
923 {
924 my($type_num, $collength) = @_;
925  
926 if(exists $Numeric_Precision{$type_num})
927 {
928 return $Numeric_Precision{$type_num};
929 }
930  
931 if($type_num == DECIMAL || $type_num == MONEY)
932 {
933 return int($collength / 256);
934 }
935  
936 return undef;
937 }
938  
939 # create procedure 'informix'.ansinumscale(coltype smallint, collength smallint)
940 # returning int;
941 #
942 # if (coltype >= 256) then
943 # let coltype = coltype - 256;
944 # end if;
945 #
946 # if (coltype = 1) or (coltype = 2) or
947 # (coltype = 6) then
948 # return 0;
949 # elif (coltype = 5) or (coltype = 8) then
950 # return (collength - ((trunc(collength / 256))*256));
951 # else
952 # return NULL;
953 # end if;
954 # end procedure
955 # document
956 # 'returns the scale of a numeric column',
957 # 'Synopsis: ansinumscale(smallint, smallint) returns int';
958  
959 sub _ix_numeric_scale
960 {
961 my($type_num, $collength) = @_;
962  
963 if($type_num == SMALLINT || $type_num == INTEGER ||
964 $type_num == SERIAL)
965 {
966 return 0;
967 }
968  
969 if($type_num == DECIMAL || $type_num == MONEY)
970 {
971 return $collength - ((int($collength / 256)) * 256);
972 }
973  
974 return undef;
975 }
976  
977 # create procedure 'informix'.ansinumprecradix( coltype smallint)
978 # returning int;
979 #
980 # if (coltype >= 256) then
981 # let coltype = coltype - 256;
982 # end if;
983 #
984 # if (coltype = 1) or (coltype = 2) or
985 # (coltype = 5) or (coltype = 6) or
986 # (coltype = 8) then
987 # return 10;
988 # elif (coltype = 3) or (coltype = 4) then
989 # return 2;
990 # else
991 # return NULL;
992 # end if;
993 # end procedure
994 # document
995 # 'returns the precision radix of a numeric column',
996 # 'Synopsis: ansinumprecradix(smallint) returns int';
997  
998 sub _ix_numeric_precision_radix
999 {
1000 my($type_num, $collength) = @_;
1001  
1002 if($type_num == SMALLINT || $type_num == INTEGER ||
1003 $type_num == DECIMAL || $type_num == SERIAL ||
1004 $type_num == MONEY)
1005 {
1006 return 10;
1007 }
1008  
1009 if($type_num == FLOAT || $type_num == SMALLFLOAT)
1010 {
1011 return 2;
1012 }
1013  
1014 return undef;
1015 }
1016  
1017 # create procedure 'informix'.ansimaxlen(coltype smallint, collength smallint)
1018 # returning int;
1019 #
1020 # if (coltype >= 256) then
1021 # let coltype = coltype - 256;
1022 # end if;
1023 #
1024 # if (coltype = 0) then
1025 # return collength;
1026 # elif (coltype = 13) or (coltype = 16) then
1027 # return (collength - (trunc(collength / 256))*256);
1028 # else
1029 # return NULL;
1030 # end if;
1031 # end procedure
1032 # document
1033 # 'returns the maximum length of character oriented column',
1034 # 'Synopsis: ansimaxlen(smallint, smallint) returns int';
1035  
1036 sub _ix_max_length
1037 {
1038 my($type_num, $collength) = @_;
1039  
1040 if($type_num == CHAR)
1041 {
1042 return $collength;
1043 }
1044  
1045 if($type_num == VARCHAR || $type_num == NVARCHAR)
1046 {
1047 return $collength - (int($collength / 256)) * 256;
1048 }
1049  
1050 return undef;
1051 }
1052  
1053 # create procedure 'informix'.ansidatprec(coltype smallint, collength smallint)
1054 # returning int;
1055 #
1056 # { if the column is nullable then coltype = coltype+256 }
1057 #
1058 # if (coltype = 7 or coltype = 263) then
1059 # return 0;
1060 # elif (coltype = 10 or coltype = 266) then
1061 # let collength = collength - 16*trunc(collength/16) - 10;
1062 # if (collength > 0) then
1063 # return collength;
1064 # else
1065 # return 0;
1066 # end if;
1067 # else
1068 # return NULL;
1069 # end if;
1070 # end procedure
1071 # document
1072 # 'returns the date precision for a datetime column',
1073 # 'Synopsis: ansidatprec(smallint, smallint) returns int';
1074  
1075 # Don't seem to need this...
1076 # sub _ix_datetime_precision
1077 # {
1078 # my($type_num, $collength) = @_;
1079 #
1080 # if($type_num == DATE)
1081 # {
1082 # return 0;
1083 # }
1084 #
1085 # if($type_num == DATETIME)
1086 # {
1087 # $collength = $collength - (16 * int($collength / 16)) - 10;
1088 #
1089 # if($collength > 0)
1090 # {
1091 # return $collength;
1092 # }
1093 #
1094 # return 0;
1095 # }
1096 #
1097 # return undef;
1098 # }
1099  
1100 # For columns of type DATETIME or INTERVAL, collength is determined using
1101 # the following formula:
1102 #
1103 # (length * 256) + (largest_qualifier_value * 16) + smallest_qualifier_value
1104 #
1105 # The length is the physical length of the DATETIME or INTERVAL field, and
1106 # largest_qualifier and smallest_qualifier have the values shown in the
1107 # following table.
1108 #
1109 # Field Qualifier Value
1110 # YEAR 0
1111 # MONTH 2
1112 # DAY 4
1113 # HOUR 6
1114 # MINUTE 8
1115 # SECOND 10
1116 # FRACTION(1) 11
1117 # FRACTION(2) 12
1118 # FRACTION(3) 13
1119 # FRACTION(4) 14
1120 # FRACTION(5) 15
1121 #
1122 # For example, if a DATETIME YEAR TO MINUTE column has a length of 12
1123 # (such as YYYY:DD:MM:HH:MM), a largest_qualifier value of 0 (for YEAR),
1124 # and a smallest_qualifier value of 8 (for MINUTE), the collength value is
1125 # 3080, or (256 * 12) + (0 * 16) + 8.
1126 #
1127 # The above is all just a fancy way of saying:
1128 #
1129 # largest_qualifier_value = (collength & 0xF0) >> 4
1130 # smallest_qualifier_value = collength & 0xF
1131 #
1132  
1133 sub _ix_datetime_specific_type
1134 {
1135 my($meta, $type_num, $collength, $col_info) = @_;
1136  
1137 return unless($type_num == DATETIME);
1138  
1139 my $largest_qualifier = ($collength & 0xF0) >> 4;
1140 my $smallest_qualifier = $collength & 0xF;
1141  
1142 unless(exists $Datetime_Qualifiers{$largest_qualifier} &&
1143 exists $Datetime_Qualifiers{$smallest_qualifier})
1144 {
1145 die "No datetime qualifier(s) found for collength $collength";
1146 }
1147  
1148 # Handle DATETIME HOUR TO (MINUTE|SECOND|FRACTION(1-5)) as a "time" column.
1149 if($largest_qualifier == $Datetime_Qualifiers_Reverse{'hour'} &&
1150 ($smallest_qualifier == $Datetime_Qualifiers_Reverse{'minute'} ||
1151 $smallest_qualifier == $Datetime_Qualifiers_Reverse{'second'} ||
1152 ($smallest_qualifier >= MIN_DATETIME_FRACTION &&
1153 $smallest_qualifier <= MAX_DATETIME_FRACTION)))
1154 {
1155 if($smallest_qualifier >= MIN_DATETIME_FRACTION &&
1156 $smallest_qualifier <= MAX_DATETIME_FRACTION)
1157 {
1158 $col_info->{'TIME_SCALE'} = $smallest_qualifier - FRACTION_SCALE_DELTA;
1159 }
1160 else
1161 {
1162 delete $col_info->{'TIME_SCALE'};
1163  
1164 if($smallest_qualifier == $Datetime_Qualifiers_Reverse{'minute'})
1165 {
1166 $col_info->{'TIME_PRECISION'} = 4; # HH:MM
1167 }
1168 }
1169  
1170 return 'time';
1171 }
1172  
1173 my $type = "datetime $Datetime_Qualifiers{$largest_qualifier} to $Datetime_Qualifiers{$smallest_qualifier}";
1174  
1175 # Punt on unsupported datetime column granularities
1176 unless($meta->column_type_class($type))
1177 {
1178 return 'scalar';
1179 }
1180  
1181 return $type;
1182 }
1183  
1184 1;