Dear Tim,

Inspired by Steffen's DBI::DBD::write_getinfo_pm function, I've
assembled a parallel function to generate the data for type_info_all.
I've called the function DBI::DBD::TypeInfo::write_typeinfo().  This
will help DBI driver writers write the method semi-automatically,
provided that their database has a decent ODBC driver.

It takes the output from DBD::ODBC's type_info_all method and maps it
writes a new copy of the hash.  I actually wrote it to handle the extra
attributes you documented, and was pleasantly surprised to find
DBD::ODBC 1.01 already providing the extra attributes (possibly simply
because the ODBC driver I was using provided them too, but maybe there
was more to it than that).  I left that code in place to handle future
additions automatically, and older ODBC drivers, etc.  It even manages
to generate the names of the SQL_INTEGER etc functions - there was a
useful note in the DBI specification which indicates how to do it.
However, I think you should mention the 'use DBI qw(:sql_types);'
notation in the DBI POD more explicitly.

At the moment, it is in a file TypeInfo.pm, and would therefore be
DBI::DBD::TypeInfo.pm.  Obviously, we could revisit that location -- or
we could think about relocating both it and DBD::DBD::write_getinfo_pm
into a single new module -- I'd recommend DBI::DBD::Metadata as the
module, and method names write_getinfo and write_typeinfo.  To a large
extent, how you deal with that is up to you, Tim.

Can anyone explain the bit in the type_info method description (cribbed
from the ODBC documentation, I'm sure) about 'ordered by DATA_TYPE first
and then by how closely each type maps to the corresponding ODBC SQL
data type, closest first'.  What the h-e-double-toothpicks does that
mean?

Ultimately, I think that the code for type_info() should be another
function that's generated by write_typeinfo, but I'm not sure how to go
about it at the moment.

The write_typeinfo function does not currently generate any POD
documentation.  It probably should.

-- 
Jonathan Leffler                           #include <disclaimer.h>
STSM, Informix Database Engineering, IBM Data Management
Phone: +1 650-926-6921   Fax: +1 650-926-6971   Tie-line: 630-6921
Email: [EMAIL PROTECTED]
Guardian of DBD::Informix v1.04.PC1 -- http://dbi.perl.org
#!/usr/bin/perl -w
#
# $Id: TypeInfo.pm,v 100.4 2002/12/18 02:54:30 jleffler Exp $
#
# Copyright (c) 2002 Jonathan Leffler
#
# Generate driver-specific type_info_all data via DBD::ODBC
#
# Modelled after write_getinfo_pm from DBI::DBD.
#
# You may distribute under the terms of either the GNU General Public
# License or the Artistic License, as specified in the Perl README file.

=head1 NAME

DBI::DBD::TypeInfo - Generate driver-specific type_info_all data

=head1 SYNOPSIS

  perl -MDBI::DBD::TypeInfo -e 'write_typeinfo($driver, $dsn, $user, $pass)'

=head1 DESCRIPTION

The C<write_typeinfo> method in the DBI::DBD::Typeinfo module generates
on standard output the data needed for a driver's typeinfo_all method.
It also provides default implementations of the typeinfo_all and typeinfo
methods for inclusion in the driver's main implementation file.

The driver parameter is the name of the driver for which the methods
will be generated; for the sake of examples, this will be "Driver".
Typically, the dsn parameter will be of the form "dbi:ODBC:odbc_dsn",
where the odbc_dsn is a DSN for one of the driver's databases.
The user and pass parameters are the other optional connection
parameters that will be provided to the DBI connect method.

Once you are sure that it is producing semi-sane data, you would
typically redirect the standard output to lib/DBD/Driver/TypeInfo.pm,
and then hand edit the result if necessary.
Do not forget to update your Makefile.PL and MANIFEST to include this as
an extra PM file that should be installed.

Please take a critical look at the data returned!
ODBC drivers vary dramatically in their quality.

The generator assumes that all the values are static and places these
values directly in the %info hash.

A possible implementation of DBD::Driver::get_info() may look like:

  sub type_info_all {
    my($dbh, $info_type) = @_;
    require DBD::Driver::TypeInfo;
    return = $DBD::Driver::TypeInfo::type_info_all;
  }

Please replace Driver (or "<foo>") with the name of your driver.
Note that this stub function is generated for you by the write_typeinfo
function, but you must manually transfer the code to Driver.pm.


=head1 AUTHORS

Jonathan Leffler <[EMAIL PROTECTED]>

=cut

package DBI::DBD::TypeInfo;

use strict;
use DBI;

our $VERSION = "1.00";

# These two are used by fmt_value...
our %dbi_inv;
our %sql_type_inv;

#-DEBUGGING-#
#sub print_hash
#{
#   my ($name, %hash) = @_;
#   print "Hash: $name\n";
#   foreach my $key (keys %hash)
#   {
#       print "$key => $hash{$key}\n";
#   }
#}
#-DEBUGGING-#

sub inverse_hash
{
    my (%hash) = @_;
    my (%inv);
    foreach my $key (keys %hash)
    {
        my $val = $hash{$key};
        die "Double mapping for key value $val ($inv{$val}, $key)!"
            if (defined $inv{$val});
        $inv{$val} = $key;
    }
    return %inv;
}

sub fmt_value
{
    my ($num, $val) = @_;
    if (!defined $val)
    {
        $val = "undef";
    }
    elsif ($val !~ m/^[-+]?\d+$/)
    {
        # All the numbers in type_info_all are integers!
        # Anything that isn't an integer is a string.
        # Ensure that no double quotes screw things up.
        $val =~ s/"/\\"/g if ($val =~ m/"/o);
        $val = qq{"$val"};
    }
    elsif ($dbi_inv{$num} =~ m/^(SQL_)?DATA_TYPE$/)
    {
        # All numeric...
        $val = $sql_type_inv{$val}
            if (defined $sql_type_inv{$val});
    }
    return $val;
}

sub write_typeinfo
{

    my ($driver, $dsn, $user, $pass) = @_ ? @_ : @ARGV;
    my $dbh = DBI->connect($dsn, $user, $pass, {AutoCommit=>1, RaiseError=>1});
    $driver = "<foo>" unless defined $driver;

    print <<PERL;

# Transfer this to ${driver}.pm

# The type_info_all function was automatically generated by
# DBI::DBD::TypeInfo::write_typeinfo v$DBI::DBD::TypeInfo::VERSION.

package DBD::${driver}::db;         # This line can be removed once transferred.

    sub type_info_all
    {
        my(\$dbh, \$info_type) = \@_;
        require DBD::${driver}::TypeInfo;
        return \$DBD::${driver}::TypeInfo::type_info_all;
    }

# Transfer this to lib/DBD/${driver}/TypeInfo.pm.
# Don't forget to add version and intellectual property control information.

# The \%type_info_all hash was automatically generated by
# DBI::DBD::TypeInfo::write_typeinfo v$DBI::DBD::TypeInfo::VERSION.

package DBD::${driver}::TypeInfo;

{
    require Exporter;
    require DynaLoader;
    \@ISA = qw(Exporter DynaLoader);
    \@EXPORT = qw(type_info_all);
    use DBI (:sql_types);

PERL

    # Generate SQL type name mapping hashes.
        # See code fragment in DBI specification.
    my %sql_type_map;
    foreach (@{$DBI::EXPORT_TAGS{sql_types}})
    {
        no strict 'refs';
        $sql_type_map{$_} = &{"DBI::$_"}();
        $sql_type_inv{$sql_type_map{$_}} = $_;
    }
    #-DEBUG-# print_hash("sql_type_map", %sql_type_map);
    #-DEBUG-# print_hash("sql_type_inv", %sql_type_inv);

    my %dbi_map =
        (
            TYPE_NAME          =>  0,
            DATA_TYPE          =>  1,
            COLUMN_SIZE        =>  2,
            LITERAL_PREFIX     =>  3,
            LITERAL_SUFFIX     =>  4,
            CREATE_PARAMS      =>  5,
            NULLABLE           =>  6,
            CASE_SENSITIVE     =>  7,
            SEARCHABLE         =>  8,
            UNSIGNED_ATTRIBUTE =>  9,
            FIXED_PREC_SCALE   => 10,
            AUTO_UNIQUE_VALUE  => 11,
            LOCAL_TYPE_NAME    => 12,
            MINIMUM_SCALE      => 13,
            MAXIMUM_SCALE      => 14,
            SQL_DATA_TYPE      => 15,
            SQL_DATETIME_SUB   => 16,
            NUM_PREC_RADIX     => 17,
            INTERVAL_PRECISION => 18,
        );

    #-DEBUG-# print_hash("dbi_map", %dbi_map);

    %dbi_inv = inverse_hash(%dbi_map);

    #-DEBUG-# print_hash("dbi_inv", %dbi_inv);

    my $maxlen = 0;
    foreach my $key (keys %dbi_map)
    {
        $maxlen = length($key) if length($key) > $maxlen;
    }

    # Print the name/value mapping entry in the type_info_all array;
    my $fmt = "            \%-${maxlen}s => \%2d,\n";
    my $numkey = 0;
    my $maxkey = 0;
    print "    our \$type_info_all = [\n        {\n";
    foreach my $i (sort { $a <=> $b } keys %dbi_inv)
    {
        printf($fmt, $dbi_inv{$i}, $i);
        $numkey++;
        $maxkey = $i;
    }
    print "        },\n";

    print STDERR "### WARNING - Non-dense set of keys ($numkey keys, $maxkey max 
key)\n"
        unless $numkey = $maxkey + 1;

    my $h = $dbh->type_info_all;
    my @tia = @$h;
    my %odbc_map = %{$tia[0]};
    shift @tia;     # Remove the mapping reference.
    my $numtyp = $#tia;

    #-DEBUG-# print_hash("odbc_map", %odbc_map);

    # In theory, the key/number mapping sequence for %dbi_map
    # should be the same as the one from the ODBC driver.  However, to
    # prevent the possibility of mismatches, and to deal with older
    # missing attributes or unexpected new ones, we chase back through
    # the %dbi_inv and %odbc_map hashes, generating @dbi_to_odbc
    # to map our new key number to the old one.
    # Report if @dbi_to_odbc is not an identity mapping.
    my @dbi_to_odbc;
    foreach my $num (sort { $a <=> $b } keys %dbi_inv)
    {
        # Find the name in %dbi_inv that matches this index number.
        my $dbi_key = $dbi_inv{$num};
        #-DEBUG-# print "dbi_key = $dbi_key\n";
        #-DEBUG-# print "odbc_key = $odbc_map{$dbi_key}\n";
        # Find the index in %odbc_map that has this key.
        $dbi_to_odbc[$num] = (defined $odbc_map{$dbi_key}) ? $odbc_map{$dbi_key} : 
undef;
    }

    # Determine the length of the longest formatted value in each field
    my @len;
    for (my $i = 0; $i <= $numtyp; $i++)
    {
        my @odbc_val = @{$tia[$i]};
        my $pad = "";
        for (my $num = 0; $num <= $maxkey; $num++)
        {
            # Find the value of the entry in the @odbc_val array.
            my $val = (defined $dbi_to_odbc[$num]) ? $odbc_val[$dbi_to_odbc[$num]] : 
undef;
            $val = fmt_value($num, $val);
            #-DEBUG-# print "val = $val\n";
            $val = "$pad$val";
            $len[$num] = length($val) if !defined $len[$num] || length($val) > 
$len[$num];
            $pad = ", ";
        }
    }

    # Generate format strings to left justify each string in maximum field width.
    my @fmt;
    for (my $i = 0; $i <= $maxkey; $i++)
    {
        $fmt[$i] = "%-$len[$i]s";
        #-DEBUG-# print "fmt[$i] = $fmt[$i]\n";
    }

    # Format the data from type_info_all
    for (my $i = 0; $i <= $numtyp; $i++)
    {
        my @odbc_val = @{$tia[$i]};
        my $pad = "";
        print "        [ ";
        for (my $num = 0; $num <= $maxkey; $num++)
        {
            # Find the value of the entry in the @odbc_val array.
            my $val = (defined $dbi_to_odbc[$num]) ? $odbc_val[$dbi_to_odbc[$num]] : 
undef;
            $val = fmt_value($num, $val);
            printf $fmt[$num], "$pad$val";
            $pad = ", ";
        }
        print " ],\n";
    }

    print "    ];\n\n    1;\n}\n\n__END__\n";

}

1;

__END__

Reply via email to