home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / Metadata.pm < prev    next >
Encoding:
Perl POD Document  |  2004-02-01  |  15.1 KB  |  491 lines

  1. package DBI::DBD::Metadata;
  2.  
  3. # $Id: Metadata.pm,v 1.5 2004/02/01 11:16:16 timbo Exp $
  4. #
  5. # Copyright (c) 1997-2003 Jonathan Leffler, Jochen Wiedmann,
  6. # Steffen Goeldner and Tim Bunce
  7. #
  8. # You may distribute under the terms of either the GNU General Public
  9. # License or the Artistic License, as specified in the Perl README file.
  10.  
  11. use Exporter ();
  12. use Carp;
  13.  
  14. use DBI;
  15. use DBI::Const::GetInfoType qw(%GetInfoType);
  16.  
  17. # Perl 5.005_03 does not recognize 'our'
  18. @ISA = qw(Exporter);
  19. @EXPORT = qw(write_getinfo_pm write_typeinfo_pm);
  20.  
  21. use strict;
  22.  
  23. my
  24. $VERSION = sprintf("%d.%02d", q$Revision: 1.5 $ =~ /(\d+)\.(\d+)/);
  25.  
  26. =head1 NAME
  27.  
  28. DBI::DBD::Metadata - Generate the code and data for some DBI metadata methods
  29.  
  30. =head1 SYNOPSIS
  31.  
  32. The idea is to extract metadata information from a good quality
  33. ODBC driver and use it to generate code and data to use in your own
  34. DBI driver for the same database.
  35.  
  36. For generating code to support the get_info method:
  37.  
  38.   perl -MDBI::DBD::Metadata -e "write_getinfo_pm('dbi:ODBC:dsn-name','user','pass','Driver')"
  39.  
  40.   perl -MDBI::DBD::Metadata -e write_getinfo_pm dbi:ODBC:foo_db username password Driver
  41.  
  42. For generating code to support the type_info method:
  43.  
  44.   perl -MDBI::DBD::Metadata -e "write_typeinfo_pm('dbi:ODBC:dsn-name','user','pass','Driver')"
  45.  
  46.   perl -MDBI::DBD::Metadata -e write_typeinfo_pm dbi:ODBC:dsn-name user pass Driver
  47.  
  48. Where C<dbi:ODBC:dsn-name> is the connection to use to extract the
  49. data, and C<Driver> is the name of the driver you want the code
  50. generated for (the driver name gets embedded into the output in
  51. many places).
  52.  
  53. =head1 Generating a GetInfo package for a driver
  54.  
  55. The C<write_getinfo_pm> in the DBI::DBD::Metadata module generates a
  56. DBD::Driver::GetInfo package on standard output.
  57.  
  58. This method generates a DBD::Driver::GetInfo package from the data
  59. source you specified in the parameter list or in the environment
  60. variable DBI_DSN.
  61. DBD::Driver::GetInfo should help a DBD author implementing the DBI
  62. get_info() method.
  63. Because you are just creating this package, it's very unlikely that
  64. DBD::Driver already provides a good implementation for get_info().
  65. Thus you will probably connect via DBD::ODBC.
  66.  
  67. Once you are sure that it is producing semi-sane data, you would
  68. typically redirect the standard output to lib/DBD/Driver/GetInfo.pm, and
  69. then hand edit the result.
  70. Do not forget to update your Makefile.PL and MANIFEST to include this as
  71. an extra PM file that should be installed.
  72.  
  73. If you connect via DBD::ODBC, you should use version 0.38 or greater;
  74.  
  75. Please take a critical look at the data returned!
  76. ODBC drivers vary dramatically in their quality.
  77.  
  78. The generator assumes that most values are static and places these
  79. values directly in the %info hash.
  80. A few examples show the use of CODE references and the implementation
  81. via subroutines.
  82. It is very likely that you have to write additional subroutines for
  83. values depending on the session state or server version, e.g.
  84. SQL_DBMS_VER.
  85.  
  86. A possible implementation of DBD::Driver::db::get_info() may look like:
  87.  
  88.   sub get_info {
  89.     my($dbh, $info_type) = @_;
  90.     require DBD::Driver::GetInfo;
  91.     my $v = $DBD::Driver::GetInfo::info{int($info_type)};
  92.     $v = $v->($dbh) if ref $v eq 'CODE';
  93.     return $v;
  94.   }
  95.  
  96. Please replace Driver (or "<foo>") with the name of your driver.
  97. Note that this stub function is generated for you by write_getinfo_pm
  98. function, but you must manually transfer the code to Driver.pm.
  99.  
  100. =cut
  101.  
  102. sub write_getinfo_pm
  103. {
  104.     my ($dsn, $user, $pass, $driver) = @_ ? @_ : @ARGV;
  105.     my $dbh = DBI->connect($dsn, $user, $pass, {RaiseError=>1});
  106.     $driver = "<foo>" unless defined $driver;
  107.  
  108.     print <<PERL;
  109.  
  110. # Transfer this to ${driver}.pm
  111.  
  112. # The get_info function was automatically generated by
  113. # DBI::DBD::Metadata::write_getinfo_pm v$DBI::DBD::Metadata::VERSION.
  114.  
  115. package DBD::${driver}::db;         # This line can be removed once transferred.
  116.  
  117.     sub get_info {
  118.         my(\$dbh, \$info_type) = \@_;
  119.         require DBD::${driver}::GetInfo;
  120.         my \$v = \$DBD::${driver}::GetInfo::info{int(\$info_type)};
  121.         \$v = \$v->(\$dbh) if ref \$v eq 'CODE';
  122.         return \$v;
  123.     }
  124.  
  125. # Transfer this to lib/DBD/${driver}/GetInfo.pm
  126.  
  127. # The \%info hash was automatically generated by
  128. # DBI::DBD::Metadata::write_getinfo_pm v$DBI::DBD::Metadata::VERSION.
  129.  
  130. package DBD::${driver}::GetInfo;
  131.  
  132. use strict;
  133. use DBD::${driver};
  134.  
  135. # Beware: not officially documented interfaces...
  136. # use DBI::Const::GetInfoType qw(\%GetInfoType);
  137. # use DBI::Const::GetInfoReturn qw(\%GetInfoReturnTypes \%GetInfoReturnValues);
  138.  
  139. my \$sql_driver = '${driver}';
  140. my \$sql_ver_fmt = '%02d.%02d.%04d';   # ODBC version string: ##.##.#####
  141. my \$sql_driver_ver = sprintf \$sql_ver_fmt, split (/\\./, \$DBD::${driver}::VERSION);
  142. PERL
  143.  
  144. my $kw_map = 0;
  145. {
  146. # Informix CLI (ODBC) v3.81.0000 does not return a list of keywords.
  147.     local $\ = "\n";
  148.     local $, = "\n";
  149.     my ($kw) = $dbh->get_info($GetInfoType{SQL_KEYWORDS});
  150.     if ($kw)
  151.     {
  152.         print "\nmy \@Keywords = qw(\n";
  153.         print sort split /,/, $kw;
  154.         print ");\n\n";
  155.         print "sub sql_keywords {\n";
  156.         print q%    return join ',', @Keywords;%;
  157.         print "\n}\n\n";
  158.         $kw_map = 1;
  159.     }
  160. }
  161.  
  162.     print <<'PERL';
  163.  
  164. sub sql_data_source_name {
  165.     my $dbh = shift;
  166.     return "dbi:$sql_driver:" . $dbh->{Name};
  167. }
  168.  
  169. sub sql_user_name {
  170.     my $dbh = shift;
  171.     # CURRENT_USER is a non-standard attribute, probably undef
  172.     # Username is a standard DBI attribute
  173.     return $dbh->{CURRENT_USER} || $dbh->{Username};
  174. }
  175.  
  176. PERL
  177.  
  178.     print "\nour \%info = (\n";
  179.     foreach my $key (sort keys %GetInfoType)
  180.     {
  181.         my $num = $GetInfoType{$key};
  182.         my $val = eval { $dbh->get_info($num); };
  183.         if ($key eq 'SQL_DATA_SOURCE_NAME') {
  184.             $val = '\&sql_data_source_name';
  185.         }
  186.         elsif ($key eq 'SQL_KEYWORDS') {
  187.             $val = ($kw_map) ? '\&sql_keywords' : 'undef';
  188.         }
  189.         elsif ($key eq 'SQL_DRIVER_VER') {
  190.             $val = '$sql_driver_ver';
  191.         }
  192.         elsif ($key eq 'SQL_USER_NAME') {
  193.             $val = '\&sql_user_name';
  194.         }
  195.         elsif (not defined $val) {
  196.             $val = 'undef';
  197.         }
  198.         elsif ($val eq '') {
  199.             $val = "''";
  200.         }
  201.         elsif ($val =~ /\D/) {
  202.             $val =~ s/\\/\\\\/g;
  203.             $val =~ s/'/\\'/g;
  204.             $val = "'$val'";
  205.         }
  206.         printf "%s %5d => %-30s # %s\n", (($val eq 'undef') ? '#' : ' '), $num, "$val,", $key;
  207.     }
  208.     print ");\n\n1;\n\n__END__\n";
  209. }
  210.  
  211.  
  212.  
  213. =head1 Generating a TypeInfo package for a driver
  214.  
  215. The C<write_typeinfo_pm> function in the DBI::DBD::Metadata module generates
  216. on standard output the data needed for a driver's type_info_all method.
  217. It also provides default implementations of the type_info_all
  218. method for inclusion in the driver's main implementation file.
  219.  
  220. The driver parameter is the name of the driver for which the methods
  221. will be generated; for the sake of examples, this will be "Driver".
  222. Typically, the dsn parameter will be of the form "dbi:ODBC:odbc_dsn",
  223. where the odbc_dsn is a DSN for one of the driver's databases.
  224. The user and pass parameters are the other optional connection
  225. parameters that will be provided to the DBI connect method.
  226.  
  227. Once you are sure that it is producing semi-sane data, you would
  228. typically redirect the standard output to lib/DBD/Driver/TypeInfo.pm,
  229. and then hand edit the result if necessary.
  230. Do not forget to update your Makefile.PL and MANIFEST to include this as
  231. an extra PM file that should be installed.
  232.  
  233. Please take a critical look at the data returned!
  234. ODBC drivers vary dramatically in their quality.
  235.  
  236. The generator assumes that all the values are static and places these
  237. values directly in the %info hash.
  238.  
  239. A possible implementation of DBD::Driver::type_info_all() may look like:
  240.  
  241.   sub type_info_all {
  242.     my ($dbh) = @_;
  243.     require DBD::Driver::TypeInfo;
  244.     return $DBD::Driver::TypeInfo::type_info_all;
  245.   }
  246.  
  247. Please replace Driver (or "<foo>") with the name of your driver.
  248. Note that this stub function is generated for you by the write_typeinfo_pm
  249. function, but you must manually transfer the code to Driver.pm.
  250.  
  251. =cut
  252.  
  253.  
  254. # These two are used by fmt_value...
  255. my %dbi_inv;
  256. my %sql_type_inv;
  257.  
  258. #-DEBUGGING-#
  259. #sub print_hash
  260. #{
  261. #   my ($name, %hash) = @_;
  262. #   print "Hash: $name\n";
  263. #   foreach my $key (keys %hash)
  264. #   {
  265. #       print "$key => $hash{$key}\n";
  266. #   }
  267. #}
  268. #-DEBUGGING-#
  269.  
  270. sub inverse_hash
  271. {
  272.     my (%hash) = @_;
  273.     my (%inv);
  274.     foreach my $key (keys %hash)
  275.     {
  276.         my $val = $hash{$key};
  277.         die "Double mapping for key value $val ($inv{$val}, $key)!"
  278.             if (defined $inv{$val});
  279.         $inv{$val} = $key;
  280.     }
  281.     return %inv;
  282. }
  283.  
  284. sub fmt_value
  285. {
  286.     my ($num, $val) = @_;
  287.     if (!defined $val)
  288.     {
  289.         $val = "undef";
  290.     }
  291.     elsif ($val !~ m/^[-+]?\d+$/)
  292.     {
  293.         # All the numbers in type_info_all are integers!
  294.         # Anything that isn't an integer is a string.
  295.         # Ensure that no double quotes screw things up.
  296.         $val =~ s/"/\\"/g if ($val =~ m/"/o);
  297.         $val = qq{"$val"};
  298.     }
  299.     elsif ($dbi_inv{$num} =~ m/^(SQL_)?DATA_TYPE$/)
  300.     {
  301.         # All numeric...
  302.         $val = $sql_type_inv{$val}
  303.             if (defined $sql_type_inv{$val});
  304.     }
  305.     return $val;
  306. }
  307.  
  308. sub write_typeinfo_pm
  309. {
  310.     my ($dsn, $user, $pass, $driver) = @_ ? @_ : @ARGV;
  311.     my $dbh = DBI->connect($dsn, $user, $pass, {AutoCommit=>1, RaiseError=>1});
  312.     $driver = "<foo>" unless defined $driver;
  313.  
  314.     print <<PERL;
  315.  
  316. # Transfer this to ${driver}.pm
  317.  
  318. # The type_info_all function was automatically generated by
  319. # DBI::DBD::Metadata::write_typeinfo_pm v$DBI::DBD::Metadata::VERSION.
  320.  
  321. package DBD::${driver}::db;         # This line can be removed once transferred.
  322.  
  323.     sub type_info_all
  324.     {
  325.         my (\$dbh) = \@_;
  326.         require DBD::${driver}::TypeInfo;
  327.         return \$DBD::${driver}::TypeInfo::type_info_all;
  328.     }
  329.  
  330. # Transfer this to lib/DBD/${driver}/TypeInfo.pm.
  331. # Don't forget to add version and intellectual property control information.
  332.  
  333. # The \%type_info_all hash was automatically generated by
  334. # DBI::DBD::Metadata::write_typeinfo_pm v$DBI::DBD::Metadata::VERSION.
  335.  
  336. package DBD::${driver}::TypeInfo;
  337.  
  338. {
  339.     require Exporter;
  340.     require DynaLoader;
  341.     \@ISA = qw(Exporter DynaLoader);
  342.     \@EXPORT = qw(type_info_all);
  343.     use DBI (:sql_types);
  344.  
  345. PERL
  346.  
  347.     # Generate SQL type name mapping hashes.
  348.     # See code fragment in DBI specification.
  349.     my %sql_type_map;
  350.     foreach (@{$DBI::EXPORT_TAGS{sql_types}})
  351.     {
  352.         no strict 'refs';
  353.         $sql_type_map{$_} = &{"DBI::$_"}();
  354.         $sql_type_inv{$sql_type_map{$_}} = $_;
  355.     }
  356.     #-DEBUG-# print_hash("sql_type_map", %sql_type_map);
  357.     #-DEBUG-# print_hash("sql_type_inv", %sql_type_inv);
  358.  
  359.     my %dbi_map =
  360.         (
  361.             TYPE_NAME          =>  0,
  362.             DATA_TYPE          =>  1,
  363.             COLUMN_SIZE        =>  2,
  364.             LITERAL_PREFIX     =>  3,
  365.             LITERAL_SUFFIX     =>  4,
  366.             CREATE_PARAMS      =>  5,
  367.             NULLABLE           =>  6,
  368.             CASE_SENSITIVE     =>  7,
  369.             SEARCHABLE         =>  8,
  370.             UNSIGNED_ATTRIBUTE =>  9,
  371.             FIXED_PREC_SCALE   => 10,
  372.             AUTO_UNIQUE_VALUE  => 11,
  373.             LOCAL_TYPE_NAME    => 12,
  374.             MINIMUM_SCALE      => 13,
  375.             MAXIMUM_SCALE      => 14,
  376.             SQL_DATA_TYPE      => 15,
  377.             SQL_DATETIME_SUB   => 16,
  378.             NUM_PREC_RADIX     => 17,
  379.             INTERVAL_PRECISION => 18,
  380.         );
  381.  
  382.     #-DEBUG-# print_hash("dbi_map", %dbi_map);
  383.  
  384.     %dbi_inv = inverse_hash(%dbi_map);
  385.  
  386.     #-DEBUG-# print_hash("dbi_inv", %dbi_inv);
  387.  
  388.     my $maxlen = 0;
  389.     foreach my $key (keys %dbi_map)
  390.     {
  391.         $maxlen = length($key) if length($key) > $maxlen;
  392.     }
  393.  
  394.     # Print the name/value mapping entry in the type_info_all array;
  395.     my $fmt = "            \%-${maxlen}s => \%2d,\n";
  396.     my $numkey = 0;
  397.     my $maxkey = 0;
  398.     print "    \$type_info_all = [\n        {\n";
  399.     foreach my $i (sort { $a <=> $b } keys %dbi_inv)
  400.     {
  401.         printf($fmt, $dbi_inv{$i}, $i);
  402.         $numkey++;
  403.         $maxkey = $i;
  404.     }
  405.     print "        },\n";
  406.  
  407.     print STDERR "### WARNING - Non-dense set of keys ($numkey keys, $maxkey max key)\n"
  408.         unless $numkey = $maxkey + 1;
  409.  
  410.     my $h = $dbh->type_info_all;
  411.     my @tia = @$h;
  412.     my %odbc_map = %{$tia[0]};
  413.     shift @tia;     # Remove the mapping reference.
  414.     my $numtyp = $#tia;
  415.  
  416.     #-DEBUG-# print_hash("odbc_map", %odbc_map);
  417.  
  418.     # In theory, the key/number mapping sequence for %dbi_map
  419.     # should be the same as the one from the ODBC driver.  However, to
  420.     # prevent the possibility of mismatches, and to deal with older
  421.     # missing attributes or unexpected new ones, we chase back through
  422.     # the %dbi_inv and %odbc_map hashes, generating @dbi_to_odbc
  423.     # to map our new key number to the old one.
  424.     # Report if @dbi_to_odbc is not an identity mapping.
  425.     my @dbi_to_odbc;
  426.     foreach my $num (sort { $a <=> $b } keys %dbi_inv)
  427.     {
  428.         # Find the name in %dbi_inv that matches this index number.
  429.         my $dbi_key = $dbi_inv{$num};
  430.         #-DEBUG-# print "dbi_key = $dbi_key\n";
  431.         #-DEBUG-# print "odbc_key = $odbc_map{$dbi_key}\n";
  432.         # Find the index in %odbc_map that has this key.
  433.         $dbi_to_odbc[$num] = (defined $odbc_map{$dbi_key}) ? $odbc_map{$dbi_key} : undef;
  434.     }
  435.  
  436.     # Determine the length of the longest formatted value in each field
  437.     my @len;
  438.     for (my $i = 0; $i <= $numtyp; $i++)
  439.     {
  440.         my @odbc_val = @{$tia[$i]};
  441.         for (my $num = 0; $num <= $maxkey; $num++)
  442.         {
  443.             # Find the value of the entry in the @odbc_val array.
  444.             my $val = (defined $dbi_to_odbc[$num]) ? $odbc_val[$dbi_to_odbc[$num]] : undef;
  445.             $val = fmt_value($num, $val);
  446.             #-DEBUG-# print "val = $val\n";
  447.             $val = "$val,";
  448.             $len[$num] = length($val) if !defined $len[$num] || length($val) > $len[$num];
  449.         }
  450.     }
  451.  
  452.     # Generate format strings to left justify each string in maximum field width.
  453.     my @fmt;
  454.     for (my $i = 0; $i <= $maxkey; $i++)
  455.     {
  456.         $fmt[$i] = "%-$len[$i]s";
  457.         #-DEBUG-# print "fmt[$i] = $fmt[$i]\n";
  458.     }
  459.  
  460.     # Format the data from type_info_all
  461.     for (my $i = 0; $i <= $numtyp; $i++)
  462.     {
  463.         my @odbc_val = @{$tia[$i]};
  464.         print "        [ ";
  465.         for (my $num = 0; $num <= $maxkey; $num++)
  466.         {
  467.             # Find the value of the entry in the @odbc_val array.
  468.             my $val = (defined $dbi_to_odbc[$num]) ? $odbc_val[$dbi_to_odbc[$num]] : undef;
  469.             $val = fmt_value($num, $val);
  470.             printf $fmt[$num], "$val,";
  471.         }
  472.         print " ],\n";
  473.     }
  474.  
  475.     print "    ];\n\n    1;\n}\n\n__END__\n";
  476.  
  477. }
  478.  
  479. 1;
  480.  
  481. __END__
  482.  
  483. =head1 AUTHORS
  484.  
  485. Jonathan Leffler <jleffler@us.ibm.com> (previously <jleffler@informix.com>),
  486. Jochen Wiedmann <joe@ispsoft.de>,
  487. Steffen Goeldner <s.goeldner@eurodata.de>,
  488. and Tim Bunce <dbi-users@perl.org>.
  489.  
  490. =cut
  491.