�ɲɾ�����ӯ�����һ��ˣ��������С���˴��ͣ�������P���ҹ��ñ˽��ά�Բ��������˸߸ԣ�������ơ��ҹ��ñ�����ά�Բ���ˡ���˳^�ӣ������ӡ� ���ͯj�ӣ��ƺ���ӣ� ? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!PKM&1]ma:: Metadata.pmnu[package DBI::DBD::Metadata; # $Id: Metadata.pm 14213 2010-06-30 19:29:18Z Martin $ # # Copyright (c) 1997-2003 Jonathan Leffler, Jochen Wiedmann, # Steffen Goeldner and Tim Bunce # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use Exporter (); use Carp; use DBI; use DBI::Const::GetInfoType qw(%GetInfoType); our @ISA = qw(Exporter); our @EXPORT = qw(write_getinfo_pm write_typeinfo_pm); our $VERSION = "2.014214"; =head1 NAME DBI::DBD::Metadata - Generate the code and data for some DBI metadata methods =head1 SYNOPSIS The idea is to extract metadata information from a good quality ODBC driver and use it to generate code and data to use in your own DBI driver for the same database. To generate code to support the get_info method: perl -MDBI::DBD::Metadata -e "write_getinfo_pm('dbi:ODBC:dsn-name','user','pass','Driver')" perl -MDBI::DBD::Metadata -e write_getinfo_pm dbi:ODBC:foo_db username password Driver To generate code to support the type_info method: perl -MDBI::DBD::Metadata -e "write_typeinfo_pm('dbi:ODBC:dsn-name','user','pass','Driver')" perl -MDBI::DBD::Metadata -e write_typeinfo_pm dbi:ODBC:dsn-name user pass Driver Where C is the connection to use to extract the data, and C is the name of the driver you want the code generated for (the driver name gets embedded into the output in numerous places). =head1 Generating a GetInfo package for a driver The C in the DBI::DBD::Metadata module generates a DBD::Driver::GetInfo package on standard output. This method generates a DBD::Driver::GetInfo package from the data source you specified in the parameter list or in the environment variable DBI_DSN. DBD::Driver::GetInfo should help a DBD author implement the DBI get_info() method. Because you are just creating this package, it is very unlikely that DBD::Driver already provides a good implementation for get_info(). Thus you will probably connect via DBD::ODBC. Once you are sure that it is producing reasonably sane data, you should typically redirect the standard output to lib/DBD/Driver/GetInfo.pm, and then hand edit the result. Do not forget to update your Makefile.PL and MANIFEST to include this as an extra PM file that should be installed. If you connect via DBD::ODBC, you should use version 0.38 or greater; Please take a critical look at the data returned! ODBC drivers vary dramatically in their quality. The generator assumes that most values are static and places these values directly in the %info hash. A few examples show the use of CODE references and the implementation via subroutines. It is very likely that you will have to write additional subroutines for values depending on the session state or server version, e.g. SQL_DBMS_VER. A possible implementation of DBD::Driver::db::get_info() may look like: sub get_info { my($dbh, $info_type) = @_; require DBD::Driver::GetInfo; my $v = $DBD::Driver::GetInfo::info{int($info_type)}; $v = $v->($dbh) if ref $v eq 'CODE'; return $v; } Please replace Driver (or "") with the name of your driver. Note that this stub function is generated for you by write_getinfo_pm function, but you must manually transfer the code to Driver.pm. =cut sub write_getinfo_pm { my ($dsn, $user, $pass, $driver) = @_ ? @_ : @ARGV; my $dbh = DBI->connect($dsn, $user, $pass, {RaiseError=>1}); $driver = "" unless defined $driver; print <(\$dbh) if ref \$v eq 'CODE'; return \$v; } # Transfer this to lib/DBD/${driver}/GetInfo.pm # The \%info hash was automatically generated by # DBI::DBD::Metadata::write_getinfo_pm v$DBI::DBD::Metadata::VERSION. package DBD::${driver}::GetInfo; use strict; use DBD::${driver}; # Beware: not officially documented interfaces... # use DBI::Const::GetInfoType qw(\%GetInfoType); # use DBI::Const::GetInfoReturn qw(\%GetInfoReturnTypes \%GetInfoReturnValues); my \$sql_driver = '${driver}'; my \$sql_ver_fmt = '%02d.%02d.%04d'; # ODBC version string: ##.##.##### my \$sql_driver_ver = sprintf \$sql_ver_fmt, split (/\\./, \$DBD::${driver}::VERSION); PERL my $kw_map = 0; { # Informix CLI (ODBC) v3.81.0000 does not return a list of keywords. local $\ = "\n"; local $, = "\n"; my ($kw) = $dbh->get_info($GetInfoType{SQL_KEYWORDS}); if ($kw) { print "\nmy \@Keywords = qw(\n"; print sort split /,/, $kw; print ");\n\n"; print "sub sql_keywords {\n"; print q% return join ',', @Keywords;%; print "\n}\n\n"; $kw_map = 1; } } print <<'PERL'; sub sql_data_source_name { my $dbh = shift; return "dbi:$sql_driver:" . $dbh->{Name}; } sub sql_user_name { my $dbh = shift; # CURRENT_USER is a non-standard attribute, probably undef # Username is a standard DBI attribute return $dbh->{CURRENT_USER} || $dbh->{Username}; } PERL print "\nour \%info = (\n"; foreach my $key (sort keys %GetInfoType) { my $num = $GetInfoType{$key}; my $val = eval { $dbh->get_info($num); }; if ($key eq 'SQL_DATA_SOURCE_NAME') { $val = '\&sql_data_source_name'; } elsif ($key eq 'SQL_KEYWORDS') { $val = ($kw_map) ? '\&sql_keywords' : 'undef'; } elsif ($key eq 'SQL_DRIVER_NAME') { $val = "\$INC{'DBD/$driver.pm'}"; } elsif ($key eq 'SQL_DRIVER_VER') { $val = '$sql_driver_ver'; } elsif ($key eq 'SQL_USER_NAME') { $val = '\&sql_user_name'; } elsif (not defined $val) { $val = 'undef'; } elsif ($val eq '') { $val = "''"; } elsif ($val =~ /\D/) { $val =~ s/\\/\\\\/g; $val =~ s/'/\\'/g; $val = "'$val'"; } printf "%s %5d => %-30s # %s\n", (($val eq 'undef') ? '#' : ' '), $num, "$val,", $key; } print ");\n\n1;\n\n__END__\n"; } =head1 Generating a TypeInfo package for a driver The C function in the DBI::DBD::Metadata module generates on standard output the data needed for a driver's type_info_all method. It also provides default implementations of the type_info_all method 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 reasonably sane data, you should 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::type_info_all() may look like: sub type_info_all { my ($dbh) = @_; require DBD::Driver::TypeInfo; return [ @$DBD::Driver::TypeInfo::type_info_all ]; } Please replace Driver (or "") with the name of your driver. Note that this stub function is generated for you by the write_typeinfo_pm function, but you must manually transfer the code to Driver.pm. =cut # These two are used by fmt_value... my %dbi_inv; my %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_pm { my ($dsn, $user, $pass, $driver) = @_ ? @_ : @ARGV; my $dbh = DBI->connect($dsn, $user, $pass, {AutoCommit=>1, RaiseError=>1}); $driver = "" unless defined $driver; print < 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 " \$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 = map { uc $_ => $tia[0]->{$_} } keys %{$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]}; 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 = "$val,"; $len[$num] = length($val) if !defined $len[$num] || length($val) > $len[$num]; } } # 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]}; 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], "$val,"; } print " ],\n"; } print " ];\n\n 1;\n}\n\n__END__\n"; } 1; __END__ =head1 AUTHORS Jonathan Leffler (previously ), Jochen Wiedmann , Steffen Goeldner , and Tim Bunce . =cut PKM&1]`yjjSqlEngine/Developers.podnu[=head1 NAME DBI::DBD::SqlEngine::Developers - Developers documentation for DBI::DBD::SqlEngine =head1 SYNOPSIS package DBD::myDriver; use base qw(DBI::DBD::SqlEngine); sub driver { ... my $drh = $proto->SUPER::driver($attr); ... return $drh->{class}; } sub CLONE { ... } package DBD::myDriver::dr; @ISA = qw(DBI::DBD::SqlEngine::dr); sub data_sources { ... } ... package DBD::myDriver::db; @ISA = qw(DBI::DBD::SqlEngine::db); sub init_valid_attributes { ... } sub init_default_attributes { ... } sub set_versions { ... } sub validate_STORE_attr { my ($dbh, $attrib, $value) = @_; ... } sub validate_FETCH_attr { my ($dbh, $attrib) = @_; ... } sub get_myd_versions { ... } sub get_avail_tables { ... } package DBD::myDriver::st; @ISA = qw(DBI::DBD::SqlEngine::st); sub FETCH { ... } sub STORE { ... } package DBD::myDriver::Statement; @ISA = qw(DBI::DBD::SqlEngine::Statement); sub open_table { ... } package DBD::myDriver::Table; @ISA = qw(DBI::DBD::SqlEngine::Table); my %reset_on_modify = ( myd_abc => "myd_foo", myd_mno => "myd_bar", ); __PACKAGE__->register_reset_on_modify( \%reset_on_modify ); my %compat_map = ( abc => 'foo_abc', xyz => 'foo_xyz', ); __PACKAGE__->register_compat_map( \%compat_map ); sub bootstrap_table_meta { ... } sub init_table_meta { ... } sub table_meta_attr_changed { ... } sub open_data { ... } sub new { ... } sub fetch_row { ... } sub push_row { ... } sub push_names { ... } sub seek { ... } sub truncate { ... } sub drop { ... } # optimize the SQL engine by add one or more of sub update_current_row { ... } # or sub update_specific_row { ... } # or sub update_one_row { ... } # or sub insert_new_row { ... } # or sub delete_current_row { ... } # or sub delete_one_row { ... } =head1 DESCRIPTION This document describes the interface of DBI::DBD::SqlEngine for DBD developers who write DBI::DBD::SqlEngine based DBI drivers. It supplements L and L, which you should read first. =head1 CLASSES Each DBI driver must provide a package global C<< driver >> method and three DBI related classes: =over 4 =item DBI::DBD::SqlEngine::dr Driver package, contains the methods DBI calls indirectly via DBI interface: DBI->connect ('DBI:DBM:', undef, undef, {}) # invokes package DBD::DBM::dr; @DBD::DBM::dr::ISA = qw(DBI::DBD::SqlEngine::dr); sub connect ($$;$$$) { ... } Similar for C and C. Pure Perl DBI drivers derived from DBI::DBD::SqlEngine usually don't need to override any of the methods provided through the DBD::XXX::dr package. However if you need additional initialization not fitting in C and C of you're ::db class, the connect method might be the final place to be modified. =item DBI::DBD::SqlEngine::db Contains the methods which are called through DBI database handles (C<< $dbh >>). e.g., $sth = $dbh->prepare ("select * from foo"); # returns the f_encoding setting for table foo $dbh->csv_get_meta ("foo", "f_encoding"); DBI::DBD::SqlEngine provides the typical methods required here. Developers who write DBI drivers based on DBI::DBD::SqlEngine need to override the methods C<< set_versions >> and C<< init_valid_attributes >>. =item DBI::DBD::SqlEngine::TieMeta; Provides the tie-magic for C<< $dbh->{$drv_pfx . "_meta"} >>. Routes C through C<< $drv->set_sql_engine_meta() >> and C through C<< $drv->get_sql_engine_meta() >>. C is not supported, you have to execute a C statement, where applicable. =item DBI::DBD::SqlEngine::TieTables; Provides the tie-magic for tables in C<< $dbh->{$drv_pfx . "_meta"} >>. Routes C though C<< $tblClass->set_table_meta_attr() >> and C though C<< $tblClass->get_table_meta_attr() >>. C removes an attribute from the I retrieved by C<< $tblClass->get_table_meta() >>. =item DBI::DBD::SqlEngine::st Contains the methods to deal with prepared statement handles. e.g., $sth->execute () or die $sth->errstr; =item DBI::DBD::SqlEngine::TableSource; Base class for 3rd party table sources: $dbh->{sql_table_source} = "DBD::Foo::TableSource"; =item DBI::DBD::SqlEngine::DataSource; Base class for 3rd party data sources: $dbh->{sql_data_source} = "DBD::Foo::DataSource"; =item DBI::DBD::SqlEngine::Statement; Base class for derived drivers statement engine. Implements C. =item DBI::DBD::SqlEngine::Table; Contains tailoring between SQL engine's requirements and C magic for finding the right tables and storage. Builds bridges between C handling of C, table initialization for SQL engines and I's attribute management for derived drivers. =back =head2 DBI::DBD::SqlEngine This is the main package containing the routines to initialize DBI::DBD::SqlEngine based DBI drivers. Primarily the C<< DBI::DBD::SqlEngine::driver >> method is invoked, either directly from DBI when the driver is initialized or from the derived class. package DBD::DBM; use base qw( DBI::DBD::SqlEngine ); sub driver { my ( $class, $attr ) = @_; ... my $drh = $class->SUPER::driver( $attr ); ... return $drh; } It is not necessary to implement your own driver method as long as additional initialization (e.g. installing more private driver methods) is not required. You do not need to call C<< setup_driver >> as DBI::DBD::SqlEngine takes care of it. =head2 DBI::DBD::SqlEngine::dr The driver package contains the methods DBI calls indirectly via the DBI interface (see L). DBI::DBD::SqlEngine based DBI drivers usually do not need to implement anything here, it is enough to do the basic initialization: package DBD:XXX::dr; @DBD::XXX::dr::ISA = qw (DBI::DBD::SqlEngine::dr); $DBD::XXX::dr::imp_data_size = 0; $DBD::XXX::dr::data_sources_attr = undef; $DBD::XXX::ATTRIBUTION = "DBD::XXX $DBD::XXX::VERSION by Hans Mustermann"; =head3 Methods provided by C<< DBI::DBD::SqlEngine::dr >>: =over 4 =item connect Supervises the driver bootstrap when calling DBI->connect( "dbi:Foo", , , { ... } ); First it instantiates a new driver using C. After that, initial bootstrap of the newly instantiated driver is done by $dbh->func( 0, "init_default_attributes" ); The first argument (C<0>) signals that this is the very first call to C. Modern drivers understand that and do early stage setup here after calling package DBD::Foo::db; our @DBD::Foo::db::ISA = qw(DBI::DBD::SqlEngine::db); sub init_default_attributes { my ($dbh, $phase) = @_; $dbh->SUPER::init_default_attributes($phase); ...; # own setup code, maybe separated by phases } When the C<$phase> argument is passed down until C, C recognizes a I driver and initializes the attributes from I and I<$attr> arguments passed via C<< DBI->connect( $dsn, $user, $pass, \%attr ) >>. At the end of the attribute initialization after I, C invoked C again for I: $dbh->func( 1, "init_default_attributes" ); =item data_sources Returns a list of I's using the C method of the class specified in C<< $dbh->{sql_table_source} >> or via C<\%attr>: @ary = DBI->data_sources($driver); @ary = DBI->data_sources($driver, \%attr); =item disconnect_all C doesn't have an overall driver cache, so nothing happens here at all. =back =head2 DBI::DBD::SqlEngine::db This package defines the database methods, which are called via the DBI database handle C<< $dbh >>. =head3 Methods provided by C<< DBI::DBD::SqlEngine::db >>: =over 4 =item ping Simply returns the content of the C<< Active >> attribute. Override when your driver needs more complicated actions here. =item prepare Prepares a new SQL statement to execute. Returns a statement handle, C<< $sth >> - instance of the DBD:XXX::st. It is neither required nor recommended to override this method. =item validate_FETCH_attr Called by C to allow inherited drivers do their own attribute name validation. Calling convention is similar to C and the return value is the approved attribute name. return $validated_attribute_name; In case of validation fails (e.g. accessing private attribute or similar), C is permitted to throw an exception. =item FETCH Fetches an attribute of a DBI database object. Private handle attributes must have a prefix (this is mandatory). If a requested attribute is detected as a private attribute without a valid prefix, the driver prefix (written as C<$drv_prefix>) is added. The driver prefix is extracted from the attribute name and verified against C<< $dbh->{ $drv_prefix . "valid_attrs" } >> (when it exists). If the requested attribute value is not listed as a valid attribute, this method croaks. If the attribute is valid and readonly (listed in C<< $dbh->{ $drv_prefix . "readonly_attrs" } >> when it exists), a real copy of the attribute value is returned. So it's not possible to modify C from outside of DBI::DBD::SqlEngine::db or a derived class. =item validate_STORE_attr Called by C to allow inherited drivers do their own attribute name validation. Calling convention is similar to C and the return value is the approved attribute name followed by the approved new value. return ($validated_attribute_name, $validated_attribute_value); In case of validation fails (e.g. accessing private attribute or similar), C is permitted to throw an exception (C throws an exception when someone tries to assign value other than C to C<< $dbh->{sql_identifier_case} >> or C<< $dbh->{sql_quoted_identifier_case} >>). =item STORE Stores a database private attribute. Private handle attributes must have a prefix (this is mandatory). If a requested attribute is detected as a private attribute without a valid prefix, the driver prefix (written as C<$drv_prefix>) is added. If the database handle has an attribute C<${drv_prefix}_valid_attrs> - for attribute names which are not listed in that hash, this method croaks. If the database handle has an attribute C<${drv_prefix}_readonly_attrs>, only attributes which are not listed there can be stored (once they are initialized). Trying to overwrite such an immutable attribute forces this method to croak. An example of a valid attributes list can be found in C<< DBI::DBD::SqlEngine::db::init_valid_attributes >>. =item set_versions This method sets the attributes C<< f_version >>, C<< sql_nano_version >>, C<< sql_statement_version >> and (if not prohibited by a restrictive C<< ${prefix}_valid_attrs >>) C<< ${prefix}_version >>. This method is called at the end of the C<< connect () >> phase. When overriding this method, do not forget to invoke the superior one. =item init_valid_attributes This method is called after the database handle is instantiated as the first attribute initialization. C<< DBI::DBD::SqlEngine::db::init_valid_attributes >> initializes the attributes C and C. When overriding this method, do not forget to invoke the superior one, preferably before doing anything else. =item init_default_attributes This method is called after the database handle is instantiated to initialize the default attributes. It expects one argument: C<$phase>. If C<$phase> is not given, C of C expects this is an old-fashioned driver which isn't capable of multi-phased initialization. C<< DBI::DBD::SqlEngine::db::init_default_attributes >> initializes the attributes C, C, C, C, C, C, C and C when L is available. It sets C to the given C<$phase>. When the derived implementor class provides the attribute to validate attributes (e.g. C<< $dbh->{dbm_valid_attrs} = {...}; >>) or the attribute containing the immutable attributes (e.g. C<< $dbh->{dbm_readonly_attrs} = {...}; >>), the attributes C, C and C are added (when available) to the list of valid and immutable attributes (where C is interpreted as the driver prefix). =item get_versions This method is called by the code injected into the instantiated driver to provide the user callable driver method C<< ${prefix}versions >> (e.g. C<< dbm_versions >>, C<< csv_versions >>, ...). The DBI::DBD::SqlEngine implementation returns all version information known by DBI::DBD::SqlEngine (e.g. DBI version, Perl version, DBI::DBD::SqlEngine version and the SQL handler version). C takes the C<$dbh> as the first argument and optionally a second argument containing a table name. The second argument is not evaluated in C<< DBI::DBD::SqlEngine::db::get_versions >> itself - but might be in the future. If the derived implementor class provides a method named C, this is invoked and the return value of it is associated to the derived driver name: if (my $dgv = $dbh->{ImplementorClass}->can ("get_" . $drv_prefix . "versions") { (my $derived_driver = $dbh->{ImplementorClass}) =~ s/::db$//; $versions{$derived_driver} = &$dgv ($dbh, $table); } Override it to add more version information about your module, (e.g. some kind of parser version in case of DBD::CSV, ...), if one line is not enough room to provide all relevant information. =item sql_parser_object Returns a L instance, when C<< sql_handler >> is set to "SQL::Statement". The parser instance is stored in C<< sql_parser_object >>. It is not recommended to override this method. =item disconnect Disconnects from a database. All local table information is discarded and the C<< Active >> attribute is set to 0. =item type_info_all Returns information about all the types supported by DBI::DBD::SqlEngine. =item table_info Returns a statement handle which is prepared to deliver information about all known tables. =item list_tables Returns a list of all known table names. =item quote Quotes a string for use in SQL statements. =item commit Warns about a useless call (if warnings enabled) and returns. DBI::DBD::SqlEngine is typically a driver which commits every action instantly when executed. =item rollback Warns about a useless call (if warnings enabled) and returns. DBI::DBD::SqlEngine is typically a driver which commits every action instantly when executed. =back =head3 Attributes used by C<< DBI::DBD::SqlEngine::db >>: This section describes attributes which are important to developers of DBI Database Drivers derived from C. =over 4 =item sql_init_order This attribute contains a hash with priorities as key and an array containing the C<$dbh> attributes to be initialized during before/after other attributes. C initializes following attributes: $dbh->{sql_init_order} = { 0 => [qw( Profile RaiseError PrintError AutoCommit )], 90 => [ "sql_meta", $dbh->{$drv_pfx_meta} ? $dbh->{$drv_pfx_meta} : () ] } The default priority of not listed attribute keys is C<50>. It is well known that a lot of attributes needed to be set before some table settings are initialized. For example, for L, when using my $dbh = DBI->connect( "dbi:DBM:", undef, undef, { f_dir => "/path/to/dbm/databases", dbm_type => "BerkeleyDB", dbm_mldbm => "JSON", # use MLDBM::Serializer::JSON dbm_tables => { quick => { dbm_type => "GDBM_File", dbm_MLDBM => "FreezeThaw" } } }); This defines a known table C which uses the L backend and L as serializer instead of the overall default L and L. B all files containing the table data have to be searched in C<< $dbh->{f_dir} >>, which requires C<< $dbh->{f_dir} >> must be initialized before C<< $dbh->{sql_meta}->{quick} >> is initialized by C method of L to get C<< $dbh->{sql_meta}->{quick}->{f_dir} >> being initialized properly. =item sql_init_phase This attribute is only set during the initialization steps of the DBI Database Driver. It contains the value of the currently run initialization phase. Currently supported phases are I and I. This attribute is set in C and removed in C. =item sql_engine_in_gofer This value has a true value in case of this driver is operated via L. The impact of being operated via Gofer is a read-only driver (not read-only databases!), so you cannot modify any attributes later - neither any table settings. B you won't get an error in cases you modify table attributes, so please carefully watch C. =item sql_table_source Names a class which is responsible for delivering I and I (Database Driver related). I here refers to L, not C. See L for details. =item sql_data_source Name a class which is responsible for handling table resources open and completing table names requested via SQL statements. See L for details. =item sql_dialect Controls the dialect understood by SQL::Parser. Possible values (delivery state of SQL::Statement): * ANSI * CSV * AnyData Defaults to "CSV". Because an SQL::Parser is instantiated only once and SQL::Parser doesn't allow one to modify the dialect once instantiated, it's strongly recommended to set this flag before any statement is executed (best place is connect attribute hash). =back =head2 DBI::DBD::SqlEngine::st Contains the methods to deal with prepared statement handles: =over 4 =item bind_param Common routine to bind placeholders to a statement for execution. It is dangerous to override this method without detailed knowledge about the DBI::DBD::SqlEngine internal storage structure. =item execute Executes a previously prepared statement (with placeholders, if any). =item finish Finishes a statement handle, discards all buffered results. The prepared statement is not discarded so the statement can be executed again. =item fetch Fetches the next row from the result-set. This method may be rewritten in a later version and if it's overridden in a derived class, the derived implementation should not rely on the storage details. =item fetchrow_arrayref Alias for C<< fetch >>. =item FETCH Fetches statement handle attributes. Supported attributes (for full overview see L) are C, C, C and C. Each column is returned as C which might be wrong depending on the derived backend storage. If the statement handle has private attributes, they can be fetched using this method, too. B that statement attributes are not associated with any table used in this statement. This method usually requires extending in a derived implementation. See L or L for some example. =item STORE Allows storing of statement private attributes. No special handling is currently implemented here. =item rows Returns the number of rows affected by the last execute. This method might return C. =back =head2 DBI::DBD::SqlEngine::TableSource Provides data sources and table information on database driver and database handle level. package DBI::DBD::SqlEngine::TableSource; sub data_sources ($;$) { my ( $class, $drh, $attrs ) = @_; ... } sub avail_tables { my ( $class, $drh ) = @_; ... } The C method is called when the user invokes any of the following: @ary = DBI->data_sources($driver); @ary = DBI->data_sources($driver, \%attr); @ary = $dbh->data_sources(); @ary = $dbh->data_sources(\%attr); The C method is called when the user invokes any of the following: @names = $dbh->tables( $catalog, $schema, $table, $type ); $sth = $dbh->table_info( $catalog, $schema, $table, $type ); $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr ); $dbh->func( "list_tables" ); Every time where an C<\%attr> argument can be specified, this C<\%attr> object's C attribute is preferred over the C<$dbh> attribute or the driver default. =head2 DBI::DBD::SqlEngine::DataSource Provides base functionality for dealing with tables. It is primarily designed for allowing transparent access to files on disk or already opened (file-)streams (e.g. for DBD::CSV). Derived classes shall be restricted to similar functionality, too (e.g. opening streams from an archive, transparently compress/uncompress log files before parsing them, package DBI::DBD::SqlEngine::DataSource; sub complete_table_name ($$;$) { my ( $self, $meta, $table, $respect_case ) = @_; ... } The method C is called when first setting up the I for a table: "SELECT user.id, user.name, user.shell FROM user WHERE ..." results in opening the table C. First step of the table open process is completing the name. Let's imagine you're having a L handle with following settings: $dbh->{sql_identifier_case} = SQL_IC_LOWER; $dbh->{f_ext} = '.lst'; $dbh->{f_dir} = '/data/web/adrmgr'; Those settings will result in looking for files matching C<[Uu][Ss][Ee][Rr](\.lst)?$> in C. The scanning of the directory C and the pattern match check will be done in C by the C method. If you intend to provide other sources of data streams than files, in addition to provide an appropriate C method, a method to open the resource is required: package DBI::DBD::SqlEngine::DataSource; sub open_data ($) { my ( $self, $meta, $attrs, $flags ) = @_; ... } After the method C has been run successfully, the table's meta information are in a state which allows the table's data accessor methods will be able to fetch/store row information. Implementation details heavily depends on the table implementation, whereby the most famous is surely L. =head2 DBI::DBD::SqlEngine::Statement Derives from DBI::SQL::Nano::Statement for unified naming when deriving new drivers. No additional feature is provided from here. =head2 DBI::DBD::SqlEngine::Table Derives from DBI::SQL::Nano::Table for unified naming when deriving new drivers. You should consult the documentation of C<< SQL::Eval::Table >> (see L) to get more information about the abstract methods of the table's base class you have to override and a description of the table meta information expected by the SQL engines. =over 4 =item bootstrap_table_meta Initializes a table meta structure. Can be safely overridden in a derived class, as long as the C<< SUPER >> method is called at the end of the overridden method. It copies the following attributes from the database into the table meta data C<< $dbh->{ReadOnly} >> into C<< $meta->{readonly} >>, C and C and makes them sticky to the table. This method should be called before you attempt to map between file name and table name to ensure the correct directory, extension etc. are used. =item init_table_meta Initializes more attributes of the table meta data - usually more expensive ones (e.g. those which require class instantiations) - when the file name and the table name could mapped. =item get_table_meta Returns the table meta data. If there are none for the required table, a new one is initialized. When after bootstrapping a new I and L a mapping can be established between an existing I and the new bootstrapped one, the already existing is used and a mapping shortcut between the recent used table name and the already known table name is hold in C<< $dbh->{sql_meta_map} >>. When it fails, nothing is returned. On success, the name of the table and the meta data structure is returned. =item get_table_meta_attr Returns a single attribute from the table meta data. If the attribute name appears in C<%compat_map>, the attribute name is updated from there. =item set_table_meta_attr Sets a single attribute in the table meta data. If the attribute name appears in C<%compat_map>, the attribute name is updated from there. =item table_meta_attr_changed Called when an attribute of the meta data is modified. If the modified attribute requires to reset a calculated attribute, the calculated attribute is reset (deleted from meta data structure) and the I flag is removed, too. The decision is made based on C<%register_reset_on_modify>. =item register_reset_on_modify Allows C to reset meta attributes when special attributes are modified. For DBD::File, modifying one of C, C, C or C will reset C. DBD::DBM extends the list for C and C to reset the value of C. If your DBD has calculated values in the meta data area, then call C: my %reset_on_modify = ( "xxx_foo" => "xxx_bar" ); __PACKAGE__->register_reset_on_modify( \%reset_on_modify ); =item register_compat_map Allows C and C to update the attribute name to the current favored one: # from DBD::DBM my %compat_map = ( "dbm_ext" => "f_ext" ); __PACKAGE__->register_compat_map( \%compat_map ); =item open_data Called to open the table's data storage. This is silently forwarded to C<< $meta->{sql_data_source}->open_data() >>. After this is done, a derived class might add more steps in an overridden C<< open_file >> method. =item new Instantiates the table. This is done in 3 steps: 1. get the table meta data 2. open the data file 3. bless the table data structure using inherited constructor new It is not recommended to override the constructor of the table class. Find a reasonable place to add you extensions in one of the above four methods. =back =head1 AUTHOR The module DBI::DBD::SqlEngine is currently maintained by H.Merijn Brand < h.m.brand at xs4all.nl > and Jens Rehsack < rehsack at googlemail.com > =head1 COPYRIGHT AND LICENSE Copyright (C) 2010 by H.Merijn Brand & Jens Rehsack All rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =cut PKM&1]SK*K*SqlEngine/HowTo.podnu[=head1 NAME DBI::DBD::SqlEngine::HowTo - Guide to create DBI::DBD::SqlEngine based driver =head1 SYNOPSIS perldoc DBI::DBD::SqlEngine::HowTo perldoc DBI perldoc DBI::DBD perldoc DBI::DBD::SqlEngine::Developers perldoc SQL::Eval perldoc DBI::DBD::SqlEngine perldoc DBI::DBD::SqlEngine::HowTo perldoc SQL::Statement::Embed =head1 DESCRIPTION This document provides a step-by-step guide, how to create a new C based DBD. It expects that you carefully read the L documentation and that you're familiar with L and had read and understood L. This document addresses experienced developers who are really sure that they need to invest time when writing a new DBI Driver. Writing a DBI Driver is neither a weekend project nor an easy job for hobby coders after work. Expect one or two man-month of time for the first start. Those who are still reading, should be able to sing the rules of L. =head1 CREATING DRIVER CLASSES Do you have an entry in DBI's DBD registry? DBI::DBD::SqlEngine expect having a unique prefix for every driver class in inheritance chain. It's easy to get a prefix - just drop the DBI team a note (L). If you want for some reason hide your work, take a look at L how to wrap a private prefix method around existing C. For this guide, a prefix of C is assumed. =head2 Sample Skeleton package DBD::Foo; use strict; use warnings; use vars qw($VERSION); use base qw(DBI::DBD::SqlEngine); use DBI (); $VERSION = "0.001"; package DBD::Foo::dr; use vars qw(@ISA $imp_data_size); @ISA = qw(DBI::DBD::SqlEngine::dr); $imp_data_size = 0; package DBD::Foo::db; use vars qw(@ISA $imp_data_size); @ISA = qw(DBI::DBD::SqlEngine::db); $imp_data_size = 0; package DBD::Foo::st; use vars qw(@ISA $imp_data_size); @ISA = qw(DBI::DBD::SqlEngine::st); $imp_data_size = 0; package DBD::Foo::Statement; use vars qw(@ISA); @ISA = qw(DBI::DBD::SqlEngine::Statement); package DBD::Foo::Table; use vars qw(@ISA); @ISA = qw(DBI::DBD::SqlEngine::Table); 1; Tiny, eh? And all you have now is a DBD named foo which will is able to deal with temporary tables, as long as you use L. In L environments, this DBD can do nothing. =head2 Deal with own attributes Before we start doing usable stuff with our DBI driver, we need to think about what we want to do and how we want to do it. Do we need tunable knobs accessible by users? Do we need status information? All this is handled in attributes of the database handles (be careful when your DBD is running "behind" a L proxy). How come the attributes into the DBD and how are they fetchable by the user? Good question, but you should know because you've read the L documentation. C and C taking care for you - all they need to know is which attribute names are valid and mutable or immutable. Tell them by adding C to your db class: sub init_valid_attributes { my $dbh = $_[0]; $dbh->SUPER::init_valid_attributes (); $dbh->{foo_valid_attrs} = { foo_version => 1, # contains version of this driver foo_valid_attrs => 1, # contains the valid attributes of foo drivers foo_readonly_attrs => 1, # contains immutable attributes of foo drivers foo_bar => 1, # contains the bar attribute foo_baz => 1, # contains the baz attribute foo_manager => 1, # contains the manager of the driver instance foo_manager_type => 1, # contains the manager class of the driver instance }; $dbh->{foo_readonly_attrs} = { foo_version => 1, # ensure no-one modifies the driver version foo_valid_attrs => 1, # do not permit one to add more valid attributes ... foo_readonly_attrs => 1, # ... or make the immutable mutable foo_manager => 1, # manager is set internally only }; return $dbh; } Woooho - but now the user cannot assign new managers? This is intended, overwrite C to handle it! sub STORE ($$$) { my ( $dbh, $attrib, $value ) = @_; $dbh->SUPER::STORE( $attrib, $value ); # we're still alive, so no exception is thrown ... # by DBI::DBD::SqlEngine::db::STORE if ( $attrib eq "foo_manager_type" ) { $dbh->{foo_manager} = $dbh->{foo_manager_type}->new(); # ... probably correct some states based on the new # foo_manager_type - see DBD::Sys for an example } } But ... my driver runs without a manager until someone first assignes a C. Well, no - there're two places where you can initialize defaults: sub init_default_attributes { my ($dbh, $phase) = @_; $dbh->SUPER::init_default_attributes($phase); if( 0 == $phase ) { # init all attributes which have no knowledge about # user settings from DSN or the attribute hash $dbh->{foo_manager_type} = "DBD::Foo::Manager"; } elsif( 1 == $phase ) { # init phase with more knowledge from DSN or attribute # hash $dbh->{foo_manager} = $dbh->{foo_manager_type}->new(); } return $dbh; } So far we can prevent the users to use our database driver as data storage for anything and everything. We care only about the real important stuff for peace on earth and alike attributes. But in fact, the driver still can't do anything. It can do less than nothing - meanwhile it's not a stupid storage area anymore. =head2 User comfort C since C<0.05> consolidates all persistent meta data of a table into a single structure stored in C<< $dbh->{sql_meta} >>. While DBI::DBD::SqlEngine provides only readonly access to this structure, modifications are still allowed. Primarily DBI::DBD::SqlEngine provides access via the setters C, C, C, C, C and C. Those methods are easily accessible by the users via the C<< $dbh->func () >> interface provided by DBI. Well, many users don't feel comfortize when calling # don't require extension for tables cars $dbh->func ("cars", "f_ext", ".csv", "set_sql_engine_meta"); DBI::DBD::SqlEngine will inject a method into your driver to increase the user comfort to allow: # don't require extension for tables cars $dbh->foo_set_meta ("cars", "f_ext", ".csv"); Better, but here and there users likes to do: # don't require extension for tables cars $dbh->{foo_tables}->{cars}->{f_ext} = ".csv"; This interface is provided when derived DBD's define following in C (re-capture L): sub init_valid_attributes { my $dbh = $_[0]; $dbh->SUPER::init_valid_attributes (); $dbh->{foo_valid_attrs} = { foo_version => 1, # contains version of this driver foo_valid_attrs => 1, # contains the valid attributes of foo drivers foo_readonly_attrs => 1, # contains immutable attributes of foo drivers foo_bar => 1, # contains the bar attribute foo_baz => 1, # contains the baz attribute foo_manager => 1, # contains the manager of the driver instance foo_manager_type => 1, # contains the manager class of the driver instance foo_meta => 1, # contains the public interface to modify table meta attributes }; $dbh->{foo_readonly_attrs} = { foo_version => 1, # ensure no-one modifies the driver version foo_valid_attrs => 1, # do not permit one to add more valid attributes ... foo_readonly_attrs => 1, # ... or make the immutable mutable foo_manager => 1, # manager is set internally only foo_meta => 1, # ensure public interface to modify table meta attributes are immutable }; $dbh->{foo_meta} = "foo_tables"; return $dbh; } This provides a tied hash in C<< $dbh->{foo_tables} >> and a tied hash for each table's meta data in C<< $dbh->{foo_tables}->{$table_name} >>. Modifications on the table meta attributes are done using the table methods: sub get_table_meta_attr { ... } sub set_table_meta_attr { ... } Both methods can adjust the attribute name for compatibility reasons, e.g. when former versions of the DBD allowed different names to be used for the same flag: my %compat_map = ( abc => 'foo_abc', xyz => 'foo_xyz', ); __PACKAGE__->register_compat_map( \%compat_map ); If any user modification on a meta attribute needs reinitialization of the meta structure (in case of C these are the attributes C, C, C and C), inform DBI::DBD::SqlEngine by doing my %reset_on_modify = ( foo_xyz => "foo_bar", foo_abc => "foo_bar", ); __PACKAGE__->register_reset_on_modify( \%reset_on_modify ); The next access to the table meta data will force DBI::DBD::SqlEngine to re-do the entire meta initialization process. Any further action which needs to be taken can handled in C: sub table_meta_attr_changed { my ($class, $meta, $attrib, $value) = @_; ... $class->SUPER::table_meta_attr_changed ($meta, $attrib, $value); } This is done before the new value is set in C<$meta>, so the attribute changed handler can act depending on the old value. =head2 Dealing with Tables Let's put some life into it - it's going to be time for it. This is a good point where a quick side step to L will help to shorten the next paragraph. The documentation in SQL::Statement::Embed regarding embedding in own DBD's works pretty fine with SQL::Statement and DBI::SQL::Nano. Second look should go to L to get a picture over the driver part of the table API. Usually there isn't much to do for an easy driver. =head2 Testing Now you should have your first own DBD. Was easy, wasn't it? But does it work well? Prove it by writing tests and remember to use dbd_edit_mm_attribs from L to ensure testing even rare cases. =head1 AUTHOR This guide is written by Jens Rehsack. DBI::DBD::SqlEngine is written by Jens Rehsack using code from DBD::File originally written by Jochen Wiedmann and Jeff Zucker. The module DBI::DBD::SqlEngine is currently maintained by H.Merijn Brand < h.m.brand at xs4all.nl > and Jens Rehsack < rehsack at googlemail.com > =head1 COPYRIGHT AND LICENSE Copyright (C) 2010 by H.Merijn Brand & Jens Rehsack All rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =cut PKM&1]QGG SqlEngine.pmnu[# -*- perl -*- # # DBI::DBD::SqlEngine - A base class for implementing DBI drivers that # have not an own SQL engine # # This module is currently maintained by # # H.Merijn Brand & Jens Rehsack # # The original author is Jochen Wiedmann. # # Copyright (C) 2009-2013 by H.Merijn Brand & Jens Rehsack # Copyright (C) 2004 by Jeff Zucker # Copyright (C) 1998 by Jochen Wiedmann # # All rights reserved. # # You may distribute this module under the terms of either the GNU # General Public License or the Artistic License, as specified in # the Perl README file. require 5.008; use strict; use DBI (); require DBI::SQL::Nano; package DBI::DBD::SqlEngine; use strict; use Carp; use vars qw( @ISA $VERSION $drh %methods_installed); $VERSION = "0.06"; $drh = undef; # holds driver handle(s) once initialized DBI->setup_driver("DBI::DBD::SqlEngine"); # only needed once but harmless to repeat my %accessors = ( versions => "get_driver_versions", new_meta => "new_sql_engine_meta", get_meta => "get_sql_engine_meta", set_meta => "set_sql_engine_meta", clear_meta => "clear_sql_engine_meta", ); sub driver ($;$) { my ( $class, $attr ) = @_; # Drivers typically use a singleton object for the $drh # We use a hash here to have one singleton per subclass. # (Otherwise DBD::CSV and DBD::DBM, for example, would # share the same driver object which would cause problems.) # An alternative would be to not cache the $drh here at all # and require that subclasses do that. Subclasses should do # their own caching, so caching here just provides extra safety. $drh->{$class} and return $drh->{$class}; $attr ||= {}; { no strict "refs"; unless ( $attr->{Attribution} ) { $class eq "DBI::DBD::SqlEngine" and $attr->{Attribution} = "$class by Jens Rehsack"; $attr->{Attribution} ||= ${ $class . "::ATTRIBUTION" } || "oops the author of $class forgot to define this"; } $attr->{Version} ||= ${ $class . "::VERSION" }; $attr->{Name} or ( $attr->{Name} = $class ) =~ s/^DBD\:\://; } $drh->{$class} = DBI::_new_drh( $class . "::dr", $attr ); $drh->{$class}->STORE( ShowErrorStatement => 1 ); my $prefix = DBI->driver_prefix($class); if ($prefix) { my $dbclass = $class . "::db"; while ( my ( $accessor, $funcname ) = each %accessors ) { my $method = $prefix . $accessor; $dbclass->can($method) and next; my $inject = sprintf <<'EOI', $dbclass, $method, $dbclass, $funcname; sub %s::%s { my $func = %s->can (q{%s}); goto &$func; } EOI eval $inject; $dbclass->install_method($method); } } else { warn "Using DBI::DBD::SqlEngine with unregistered driver $class.\n" . "Reading documentation how to prevent is strongly recommended.\n"; } # XXX inject DBD::XXX::Statement unless exists my $stclass = $class . "::st"; $stclass->install_method("sql_get_colnames") unless ( $methods_installed{__PACKAGE__}++ ); return $drh->{$class}; } # driver sub CLONE { undef $drh; } # CLONE # ====== DRIVER ================================================================ package DBI::DBD::SqlEngine::dr; use strict; use warnings; use vars qw(@ISA $imp_data_size); use Carp qw/carp/; $imp_data_size = 0; sub connect ($$;$$$) { my ( $drh, $dbname, $user, $auth, $attr ) = @_; # create a 'blank' dbh my $dbh = DBI::_new_dbh( $drh, { Name => $dbname, USER => $user, CURRENT_USER => $user, } ); if ($dbh) { # must be done first, because setting flags implicitly calls $dbdname::db->STORE $dbh->func( 0, "init_default_attributes" ); my $two_phased_init; defined $dbh->{sql_init_phase} and $two_phased_init = ++$dbh->{sql_init_phase}; my %second_phase_attrs; my @func_inits; # this must be done to allow DBI.pm reblessing got handle after successful connecting exists $attr->{RootClass} and $second_phase_attrs{RootClass} = delete $attr->{RootClass}; my ( $var, $val ); while ( length $dbname ) { if ( $dbname =~ s/^((?:[^\\;]|\\.)*?);//s ) { $var = $1; } else { $var = $dbname; $dbname = ""; } if ( $var =~ m/^(.+?)=(.*)/s ) { $var = $1; ( $val = $2 ) =~ s/\\(.)/$1/g; exists $attr->{$var} and carp("$var is given in DSN *and* \$attr during DBI->connect()") if ($^W); exists $attr->{$var} or $attr->{$var} = $val; } elsif ( $var =~ m/^(.+?)=>(.*)/s ) { $var = $1; ( $val = $2 ) =~ s/\\(.)/$1/g; my $ref = eval $val; # $dbh->$var($ref); push( @func_inits, $var, $ref ); } } # The attributes need to be sorted in a specific way as the # assignment is through tied hashes and calls STORE on each # attribute. Some attributes require to be called prior to # others # e.g. f_dir *must* be done before xx_tables in DBD::File # The dbh attribute sql_init_order is a hash with the order # as key (low is first, 0 .. 100) and the attributes that # are set to that oreder as anon-list as value: # { 0 => [qw( AutoCommit PrintError RaiseError Profile ... )], # 10 => [ list of attr to be dealt with immediately after first ], # 50 => [ all fields that are unspecified or default sort order ], # 90 => [ all fields that are needed after other initialisation ], # } my %order = map { my $order = $_; map { ( $_ => $order ) } @{ $dbh->{sql_init_order}{$order} }; } sort { $a <=> $b } keys %{ $dbh->{sql_init_order} || {} }; my @ordered_attr = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, defined $order{$_} ? $order{$_} : 50 ] } keys %$attr; # initialize given attributes ... lower weighted before higher weighted foreach my $a (@ordered_attr) { exists $attr->{$a} or next; $two_phased_init and eval { $dbh->{$a} = $attr->{$a}; delete $attr->{$a}; }; $@ and $second_phase_attrs{$a} = delete $attr->{$a}; $two_phased_init or $dbh->STORE( $a, delete $attr->{$a} ); } $two_phased_init and $dbh->func( 1, "init_default_attributes" ); %$attr = %second_phase_attrs; for ( my $i = 0; $i < scalar(@func_inits); $i += 2 ) { my $func = $func_inits[$i]; my $arg = $func_inits[ $i + 1 ]; $dbh->$func($arg); } $dbh->func("init_done"); $dbh->STORE( Active => 1 ); } return $dbh; } # connect sub data_sources ($;$) { my ( $drh, $attr ) = @_; my $tbl_src; $attr and defined $attr->{sql_table_source} and $attr->{sql_table_source}->isa('DBI::DBD::SqlEngine::TableSource') and $tbl_src = $attr->{sql_table_source}; !defined($tbl_src) and $drh->{ImplementorClass}->can('default_table_source') and $tbl_src = $drh->{ImplementorClass}->default_table_source(); defined($tbl_src) or return; $tbl_src->data_sources( $drh, $attr ); } # data_sources sub disconnect_all { } # disconnect_all sub DESTROY { undef; } # DESTROY # ====== DATABASE ============================================================== package DBI::DBD::SqlEngine::db; use strict; use warnings; use vars qw(@ISA $imp_data_size); use Carp; if ( eval { require Clone; } ) { Clone->import("clone"); } else { require Storable; # in CORE since 5.7.3 *clone = \&Storable::dclone; } $imp_data_size = 0; sub ping { ( $_[0]->FETCH("Active") ) ? 1 : 0; } # ping sub data_sources { my ( $dbh, $attr, @other ) = @_; my $drh = $dbh->{Driver}; # XXX proxy issues? ref($attr) eq 'HASH' or $attr = {}; defined( $attr->{sql_table_source} ) or $attr->{sql_table_source} = $dbh->{sql_table_source}; return $drh->data_sources( $attr, @other ); } sub prepare ($$;@) { my ( $dbh, $statement, @attribs ) = @_; # create a 'blank' sth my $sth = DBI::_new_sth( $dbh, { Statement => $statement } ); if ($sth) { my $class = $sth->FETCH("ImplementorClass"); $class =~ s/::st$/::Statement/; my $stmt; # if using SQL::Statement version > 1 # cache the parser object if the DBD supports parser caching # SQL::Nano and older SQL::Statements don't support this if ( $class->isa("SQL::Statement") ) { my $parser = $dbh->{sql_parser_object}; $parser ||= eval { $dbh->func("sql_parser_object") }; if ($@) { $stmt = eval { $class->new($statement) }; } else { $stmt = eval { $class->new( $statement, $parser ) }; } } else { $stmt = eval { $class->new($statement) }; } if ( $@ || $stmt->{errstr} ) { $dbh->set_err( $DBI::stderr, $@ || $stmt->{errstr} ); undef $sth; } else { $sth->STORE( "sql_stmt", $stmt ); $sth->STORE( "sql_params", [] ); $sth->STORE( "NUM_OF_PARAMS", scalar( $stmt->params() ) ); my @colnames = $sth->sql_get_colnames(); $sth->STORE( "NUM_OF_FIELDS", scalar @colnames ); } } return $sth; } # prepare sub set_versions { my $dbh = $_[0]; $dbh->{sql_engine_version} = $DBI::DBD::SqlEngine::VERSION; for (qw( nano_version statement_version )) { defined $DBI::SQL::Nano::versions->{$_} or next; $dbh->{"sql_$_"} = $DBI::SQL::Nano::versions->{$_}; } $dbh->{sql_handler} = $dbh->{sql_statement_version} ? "SQL::Statement" : "DBI::SQL::Nano"; return $dbh; } # set_versions sub init_valid_attributes { my $dbh = $_[0]; $dbh->{sql_valid_attrs} = { sql_engine_version => 1, # DBI::DBD::SqlEngine version sql_handler => 1, # Nano or S:S sql_nano_version => 1, # Nano version sql_statement_version => 1, # S:S version sql_flags => 1, # flags for SQL::Parser sql_dialect => 1, # dialect for SQL::Parser sql_quoted_identifier_case => 1, # case for quoted identifiers sql_identifier_case => 1, # case for non-quoted identifiers sql_parser_object => 1, # SQL::Parser instance sql_sponge_driver => 1, # Sponge driver for table_info () sql_valid_attrs => 1, # SQL valid attributes sql_readonly_attrs => 1, # SQL readonly attributes sql_init_phase => 1, # Only during initialization sql_meta => 1, # meta data for tables sql_meta_map => 1, # mapping table for identifier case sql_data_source => 1, # reasonable datasource class }; $dbh->{sql_readonly_attrs} = { sql_engine_version => 1, # DBI::DBD::SqlEngine version sql_handler => 1, # Nano or S:S sql_nano_version => 1, # Nano version sql_statement_version => 1, # S:S version sql_quoted_identifier_case => 1, # case for quoted identifiers sql_parser_object => 1, # SQL::Parser instance sql_sponge_driver => 1, # Sponge driver for table_info () sql_valid_attrs => 1, # SQL valid attributes sql_readonly_attrs => 1, # SQL readonly attributes }; return $dbh; } # init_valid_attributes sub init_default_attributes { my ( $dbh, $phase ) = @_; my $given_phase = $phase; unless ( defined($phase) ) { # we have an "old" driver here $phase = defined $dbh->{sql_init_phase}; $phase and $phase = $dbh->{sql_init_phase}; } if ( 0 == $phase ) { # must be done first, because setting flags implicitly calls $dbdname::db->STORE $dbh->func("init_valid_attributes"); $dbh->func("set_versions"); $dbh->{sql_identifier_case} = 2; # SQL_IC_LOWER $dbh->{sql_quoted_identifier_case} = 3; # SQL_IC_SENSITIVE $dbh->{sql_dialect} = "CSV"; $dbh->{sql_init_phase} = $given_phase; # complete derived attributes, if required ( my $drv_class = $dbh->{ImplementorClass} ) =~ s/::db$//; my $drv_prefix = DBI->driver_prefix($drv_class); my $valid_attrs = $drv_prefix . "valid_attrs"; my $ro_attrs = $drv_prefix . "readonly_attrs"; # check whether we're running in a Gofer server or not (see # validate_FETCH_attr for details) $dbh->{sql_engine_in_gofer} = ( defined $INC{"DBD/Gofer.pm"} && ( caller(5) )[0] eq "DBI::Gofer::Execute" ); $dbh->{sql_meta} = {}; $dbh->{sql_meta_map} = {}; # choose new name because it contains other keys # init_default_attributes calls inherited routine before derived DBD's # init their default attributes, so we don't override something here # # defining an order of attribute initialization from connect time # specified ones with a magic baarier (see next statement) my $drv_pfx_meta = $drv_prefix . "meta"; $dbh->{sql_init_order} = { 0 => [qw( Profile RaiseError PrintError AutoCommit )], 90 => [ "sql_meta", $dbh->{$drv_pfx_meta} ? $dbh->{$drv_pfx_meta} : () ], }; # ensuring Profile, RaiseError, PrintError, AutoCommit are initialized # first when initializing attributes from connect time specified # attributes # further, initializations to predefined tables are happens after any # unspecified attribute initialization (that default to order 50) my @comp_attrs = qw(valid_attrs version readonly_attrs); if ( exists $dbh->{$drv_pfx_meta} and !$dbh->{sql_engine_in_gofer} ) { my $attr = $dbh->{$drv_pfx_meta}; defined $attr and defined $dbh->{$valid_attrs} and !defined $dbh->{$valid_attrs}{$attr} and $dbh->{$valid_attrs}{$attr} = 1; my %h; tie %h, "DBI::DBD::SqlEngine::TieTables", $dbh; $dbh->{$attr} = \%h; push @comp_attrs, "meta"; } foreach my $comp_attr (@comp_attrs) { my $attr = $drv_prefix . $comp_attr; defined $dbh->{$valid_attrs} and !defined $dbh->{$valid_attrs}{$attr} and $dbh->{$valid_attrs}{$attr} = 1; defined $dbh->{$ro_attrs} and !defined $dbh->{$ro_attrs}{$attr} and $dbh->{$ro_attrs}{$attr} = 1; } } return $dbh; } # init_default_attributes sub init_done { defined $_[0]->{sql_init_phase} and delete $_[0]->{sql_init_phase}; delete $_[0]->{sql_valid_attrs}->{sql_init_phase}; return; } sub sql_parser_object { my $dbh = $_[0]; my $dialect = $dbh->{sql_dialect} || "CSV"; my $parser = { RaiseError => $dbh->FETCH("RaiseError"), PrintError => $dbh->FETCH("PrintError"), }; my $sql_flags = $dbh->FETCH("sql_flags") || {}; %$parser = ( %$parser, %$sql_flags ); $parser = SQL::Parser->new( $dialect, $parser ); $dbh->{sql_parser_object} = $parser; return $parser; } # sql_parser_object sub sql_sponge_driver { my $dbh = $_[0]; my $dbh2 = $dbh->{sql_sponge_driver}; unless ($dbh2) { $dbh2 = $dbh->{sql_sponge_driver} = DBI->connect("DBI:Sponge:"); unless ($dbh2) { $dbh->set_err( $DBI::stderr, $DBI::errstr ); return; } } } sub disconnect ($) { %{ $_[0]->{sql_meta} } = (); %{ $_[0]->{sql_meta_map} } = (); $_[0]->STORE( Active => 0 ); return 1; } # disconnect sub validate_FETCH_attr { my ( $dbh, $attrib ) = @_; # If running in a Gofer server, access to our tied compatibility hash # would force Gofer to serialize the tieing object including it's # private $dbh reference used to do the driver function calls. # This will result in nasty exceptions. So return a copy of the # sql_meta structure instead, which is the source of for the compatibility # tie-hash. It's not as good as liked, but the best we can do in this # situation. if ( $dbh->{sql_engine_in_gofer} ) { ( my $drv_class = $dbh->{ImplementorClass} ) =~ s/::db$//; my $drv_prefix = DBI->driver_prefix($drv_class); exists $dbh->{ $drv_prefix . "meta" } && $attrib eq $dbh->{ $drv_prefix . "meta" } and $attrib = "sql_meta"; } return $attrib; } sub FETCH ($$) { my ( $dbh, $attrib ) = @_; $attrib eq "AutoCommit" and return 1; # Driver private attributes are lower cased if ( $attrib eq ( lc $attrib ) ) { # first let the implementation deliver an alias for the attribute to fetch # after it validates the legitimation of the fetch request $attrib = $dbh->func( $attrib, "validate_FETCH_attr" ) or return; my $attr_prefix; $attrib =~ m/^([a-z]+_)/ and $attr_prefix = $1; unless ($attr_prefix) { ( my $drv_class = $dbh->{ImplementorClass} ) =~ s/::db$//; $attr_prefix = DBI->driver_prefix($drv_class); $attrib = $attr_prefix . $attrib; } my $valid_attrs = $attr_prefix . "valid_attrs"; my $ro_attrs = $attr_prefix . "readonly_attrs"; exists $dbh->{$valid_attrs} and ( $dbh->{$valid_attrs}{$attrib} or return $dbh->set_err( $DBI::stderr, "Invalid attribute '$attrib'" ) ); exists $dbh->{$ro_attrs} and $dbh->{$ro_attrs}{$attrib} and defined $dbh->{$attrib} and refaddr( $dbh->{$attrib} ) and return clone( $dbh->{$attrib} ); return $dbh->{$attrib}; } # else pass up to DBI to handle return $dbh->SUPER::FETCH($attrib); } # FETCH sub validate_STORE_attr { my ( $dbh, $attrib, $value ) = @_; if ( $attrib eq "sql_identifier_case" || $attrib eq "sql_quoted_identifier_case" and $value < 1 || $value > 4 ) { croak "attribute '$attrib' must have a value from 1 .. 4 (SQL_IC_UPPER .. SQL_IC_MIXED)"; # XXX correctly a remap of all entries in sql_meta/sql_meta_map is required here } ( my $drv_class = $dbh->{ImplementorClass} ) =~ s/::db$//; my $drv_prefix = DBI->driver_prefix($drv_class); exists $dbh->{ $drv_prefix . "meta" } and $attrib eq $dbh->{ $drv_prefix . "meta" } and $attrib = "sql_meta"; return ( $attrib, $value ); } # the ::db::STORE method is what gets called when you set # a lower-cased database handle attribute such as $dbh->{somekey}=$someval; # # STORE should check to make sure that "somekey" is a valid attribute name # but only if it is really one of our attributes (starts with dbm_ or foo_) # You can also check for valid values for the attributes if needed # and/or perform other operations # sub STORE ($$$) { my ( $dbh, $attrib, $value ) = @_; if ( $attrib eq "AutoCommit" ) { $value and return 1; # is already set croak "Can't disable AutoCommit"; } if ( $attrib eq lc $attrib ) { # Driver private attributes are lower cased ( $attrib, $value ) = $dbh->func( $attrib, $value, "validate_STORE_attr" ); $attrib or return; my $attr_prefix; $attrib =~ m/^([a-z]+_)/ and $attr_prefix = $1; unless ($attr_prefix) { ( my $drv_class = $dbh->{ImplementorClass} ) =~ s/::db$//; $attr_prefix = DBI->driver_prefix($drv_class); $attrib = $attr_prefix . $attrib; } my $valid_attrs = $attr_prefix . "valid_attrs"; my $ro_attrs = $attr_prefix . "readonly_attrs"; exists $dbh->{$valid_attrs} and ( $dbh->{$valid_attrs}{$attrib} or return $dbh->set_err( $DBI::stderr, "Invalid attribute '$attrib'" ) ); exists $dbh->{$ro_attrs} and $dbh->{$ro_attrs}{$attrib} and defined $dbh->{$attrib} and return $dbh->set_err( $DBI::stderr, "attribute '$attrib' is readonly and must not be modified" ); if ( $attrib eq "sql_meta" ) { while ( my ( $k, $v ) = each %$value ) { $dbh->{$attrib}{$k} = $v; } } else { $dbh->{$attrib} = $value; } return 1; } return $dbh->SUPER::STORE( $attrib, $value ); } # STORE sub get_driver_versions { my ( $dbh, $table ) = @_; my %vsn = ( OS => "$^O ($Config::Config{osvers})", Perl => "$] ($Config::Config{archname})", DBI => $DBI::VERSION, ); my %vmp; my $sql_engine_verinfo = join " ", $dbh->{sql_engine_version}, "using", $dbh->{sql_handler}, $dbh->{sql_handler} eq "SQL::Statement" ? $dbh->{sql_statement_version} : $dbh->{sql_nano_version}; my $indent = 0; my @deriveds = ( $dbh->{ImplementorClass} ); while (@deriveds) { my $derived = shift @deriveds; $derived eq "DBI::DBD::SqlEngine::db" and last; $derived->isa("DBI::DBD::SqlEngine::db") or next; #no strict 'refs'; eval "push \@deriveds, \@${derived}::ISA"; #use strict; ( my $drv_class = $derived ) =~ s/::db$//; my $drv_prefix = DBI->driver_prefix($drv_class); my $ddgv = $dbh->{ImplementorClass}->can("get_${drv_prefix}versions"); my $drv_version = $ddgv ? &$ddgv( $dbh, $table ) : $dbh->{ $drv_prefix . "version" }; $drv_version ||= eval { $derived->VERSION() }; # XXX access $drv_class::VERSION via symbol table $vsn{$drv_class} = $drv_version; $indent and $vmp{$drv_class} = " " x $indent . $drv_class; $indent += 2; } $vsn{"DBI::DBD::SqlEngine"} = $sql_engine_verinfo; $indent and $vmp{"DBI::DBD::SqlEngine"} = " " x $indent . "DBI::DBD::SqlEngine"; $DBI::PurePerl and $vsn{"DBI::PurePerl"} = $DBI::PurePerl::VERSION; $indent += 20; my @versions = map { sprintf "%-${indent}s %s", $vmp{$_} || $_, $vsn{$_} } sort { $a->isa($b) and return -1; $b->isa($a) and return 1; $a->isa("DBI::DBD::SqlEngine") and return -1; $b->isa("DBI::DBD::SqlEngine") and return 1; return $a cmp $b; } keys %vsn; return wantarray ? @versions : join "\n", @versions; } # get_versions sub get_single_table_meta { my ( $dbh, $table, $attr ) = @_; my $meta; $table eq "." and return $dbh->FETCH($attr); ( my $class = $dbh->{ImplementorClass} ) =~ s/::db$/::Table/; ( undef, $meta ) = $class->get_table_meta( $dbh, $table, 1 ); $meta or croak "No such table '$table'"; # prevent creation of undef attributes return $class->get_table_meta_attr( $meta, $attr ); } # get_single_table_meta sub get_sql_engine_meta { my ( $dbh, $table, $attr ) = @_; my $gstm = $dbh->{ImplementorClass}->can("get_single_table_meta"); $table eq "*" and $table = [ ".", keys %{ $dbh->{sql_meta} } ]; $table eq "+" and $table = [ grep { m/^[_A-Za-z0-9]+$/ } keys %{ $dbh->{sql_meta} } ]; ref $table eq "Regexp" and $table = [ grep { $_ =~ $table } keys %{ $dbh->{sql_meta} } ]; ref $table || ref $attr or return $gstm->( $dbh, $table, $attr ); ref $table or $table = [$table]; ref $attr or $attr = [$attr]; "ARRAY" eq ref $table or return $dbh->set_err( $DBI::stderr, "Invalid argument for \$table - SCALAR, Regexp or ARRAY expected but got " . ref $table ); "ARRAY" eq ref $attr or return $dbh->set_err( "Invalid argument for \$attr - SCALAR or ARRAY expected but got " . ref $attr ); my %results; foreach my $tname ( @{$table} ) { my %tattrs; foreach my $aname ( @{$attr} ) { $tattrs{$aname} = $gstm->( $dbh, $tname, $aname ); } $results{$tname} = \%tattrs; } return \%results; } # get_sql_engine_meta sub new_sql_engine_meta { my ( $dbh, $table, $values ) = @_; my $respect_case = 0; "HASH" eq ref $values or croak "Invalid argument for \$values - SCALAR or HASH expected but got " . ref $values; $table =~ s/^\"// and $respect_case = 1; # handle quoted identifiers $table =~ s/\"$//; unless ($respect_case) { defined $dbh->{sql_meta_map}{$table} and $table = $dbh->{sql_meta_map}{$table}; } $dbh->{sql_meta}{$table} = { %{$values} }; my $class; defined $values->{sql_table_class} and $class = $values->{sql_table_class}; defined $class or ( $class = $dbh->{ImplementorClass} ) =~ s/::db$/::Table/; # XXX we should never hit DBD::File::Table::get_table_meta here ... my ( undef, $meta ) = $class->get_table_meta( $dbh, $table, $respect_case ); 1; } # new_sql_engine_meta sub set_single_table_meta { my ( $dbh, $table, $attr, $value ) = @_; my $meta; $table eq "." and return $dbh->STORE( $attr, $value ); ( my $class = $dbh->{ImplementorClass} ) =~ s/::db$/::Table/; ( undef, $meta ) = $class->get_table_meta( $dbh, $table, 1 ); # 1 means: respect case $meta or croak "No such table '$table'"; $class->set_table_meta_attr( $meta, $attr, $value ); return $dbh; } # set_single_table_meta sub set_sql_engine_meta { my ( $dbh, $table, $attr, $value ) = @_; my $sstm = $dbh->{ImplementorClass}->can("set_single_table_meta"); $table eq "*" and $table = [ ".", keys %{ $dbh->{sql_meta} } ]; $table eq "+" and $table = [ grep { m/^[_A-Za-z0-9]+$/ } keys %{ $dbh->{sql_meta} } ]; ref($table) eq "Regexp" and $table = [ grep { $_ =~ $table } keys %{ $dbh->{sql_meta} } ]; ref $table || ref $attr or return $sstm->( $dbh, $table, $attr, $value ); ref $table or $table = [$table]; ref $attr or $attr = { $attr => $value }; "ARRAY" eq ref $table or croak "Invalid argument for \$table - SCALAR, Regexp or ARRAY expected but got " . ref $table; "HASH" eq ref $attr or croak "Invalid argument for \$attr - SCALAR or HASH expected but got " . ref $attr; foreach my $tname ( @{$table} ) { while ( my ( $aname, $aval ) = each %$attr ) { $sstm->( $dbh, $tname, $aname, $aval ); } } return $dbh; } # set_file_meta sub clear_sql_engine_meta { my ( $dbh, $table ) = @_; ( my $class = $dbh->{ImplementorClass} ) =~ s/::db$/::Table/; my ( undef, $meta ) = $class->get_table_meta( $dbh, $table, 1 ); $meta and %{$meta} = (); return; } # clear_file_meta sub DESTROY ($) { my $dbh = shift; $dbh->SUPER::FETCH("Active") and $dbh->disconnect; undef $dbh->{sql_parser_object}; } # DESTROY sub type_info_all ($) { [ { TYPE_NAME => 0, DATA_TYPE => 1, PRECISION => 2, LITERAL_PREFIX => 3, LITERAL_SUFFIX => 4, CREATE_PARAMS => 5, NULLABLE => 6, CASE_SENSITIVE => 7, SEARCHABLE => 8, UNSIGNED_ATTRIBUTE => 9, MONEY => 10, AUTO_INCREMENT => 11, LOCAL_TYPE_NAME => 12, MINIMUM_SCALE => 13, MAXIMUM_SCALE => 14, }, [ "VARCHAR", DBI::SQL_VARCHAR(), undef, "'", "'", undef, 0, 1, 1, 0, 0, 0, undef, 1, 999999, ], [ "CHAR", DBI::SQL_CHAR(), undef, "'", "'", undef, 0, 1, 1, 0, 0, 0, undef, 1, 999999, ], [ "INTEGER", DBI::SQL_INTEGER(), undef, "", "", undef, 0, 0, 1, 0, 0, 0, undef, 0, 0, ], [ "REAL", DBI::SQL_REAL(), undef, "", "", undef, 0, 0, 1, 0, 0, 0, undef, 0, 0, ], [ "BLOB", DBI::SQL_LONGVARBINARY(), undef, "'", "'", undef, 0, 1, 1, 0, 0, 0, undef, 1, 999999, ], [ "BLOB", DBI::SQL_LONGVARBINARY(), undef, "'", "'", undef, 0, 1, 1, 0, 0, 0, undef, 1, 999999, ], [ "TEXT", DBI::SQL_LONGVARCHAR(), undef, "'", "'", undef, 0, 1, 1, 0, 0, 0, undef, 1, 999999, ], ]; } # type_info_all sub get_avail_tables { my $dbh = $_[0]; my @tables = (); if ( $dbh->{sql_handler} eq "SQL::Statement" and $dbh->{sql_ram_tables} ) { # XXX map +[ undef, undef, $_, "TABLE", "TEMP" ], keys %{...} foreach my $table ( keys %{ $dbh->{sql_ram_tables} } ) { push @tables, [ undef, undef, $table, "TABLE", "TEMP" ]; } } my $tbl_src; defined $dbh->{sql_table_source} and $dbh->{sql_table_source}->isa('DBI::DBD::SqlEngine::TableSource') and $tbl_src = $dbh->{sql_table_source}; !defined($tbl_src) and $dbh->{Driver}->{ImplementorClass}->can('default_table_source') and $tbl_src = $dbh->{Driver}->{ImplementorClass}->default_table_source(); defined($tbl_src) and push( @tables, $tbl_src->avail_tables($dbh) ); return @tables; } # get_avail_tables { my $names = [qw( TABLE_QUALIFIER TABLE_OWNER TABLE_NAME TABLE_TYPE REMARKS )]; sub table_info ($) { my $dbh = shift; my @tables = $dbh->func("get_avail_tables"); # Temporary kludge: DBD::Sponge dies if @tables is empty. :-( # this no longer seems to be true @tables or return; my $dbh2 = $dbh->func("sql_sponge_driver"); my $sth = $dbh2->prepare( "TABLE_INFO", { rows => \@tables, NAME => $names, } ); $sth or return $dbh->set_err( $DBI::stderr, $dbh2->errstr ); $sth->execute or return; return $sth; } # table_info } sub list_tables ($) { my $dbh = shift; my @table_list; my @tables = $dbh->func("get_avail_tables") or return; foreach my $ref (@tables) { # rt69260 and rt67223 - the same issue in 2 different queues push @table_list, $ref->[2]; } return @table_list; } # list_tables sub quote ($$;$) { my ( $self, $str, $type ) = @_; defined $str or return "NULL"; defined $type && ( $type == DBI::SQL_NUMERIC() || $type == DBI::SQL_DECIMAL() || $type == DBI::SQL_INTEGER() || $type == DBI::SQL_SMALLINT() || $type == DBI::SQL_FLOAT() || $type == DBI::SQL_REAL() || $type == DBI::SQL_DOUBLE() || $type == DBI::SQL_TINYINT() ) and return $str; $str =~ s/\\/\\\\/sg; $str =~ s/\0/\\0/sg; $str =~ s/\'/\\\'/sg; $str =~ s/\n/\\n/sg; $str =~ s/\r/\\r/sg; return "'$str'"; } # quote sub commit ($) { my $dbh = shift; $dbh->FETCH("Warn") and carp "Commit ineffective while AutoCommit is on", -1; return 1; } # commit sub rollback ($) { my $dbh = shift; $dbh->FETCH("Warn") and carp "Rollback ineffective while AutoCommit is on", -1; return 0; } # rollback # ====== Tie-Meta ============================================================== package DBI::DBD::SqlEngine::TieMeta; use Carp qw(croak); require Tie::Hash; @DBI::DBD::SqlEngine::TieMeta::ISA = qw(Tie::Hash); sub TIEHASH { my ( $class, $tblClass, $tblMeta ) = @_; my $self = bless( { tblClass => $tblClass, tblMeta => $tblMeta, }, $class ); return $self; } # new sub STORE { my ( $self, $meta_attr, $meta_val ) = @_; $self->{tblClass}->set_table_meta_attr( $self->{tblMeta}, $meta_attr, $meta_val ); return; } # STORE sub FETCH { my ( $self, $meta_attr ) = @_; return $self->{tblClass}->get_table_meta_attr( $self->{tblMeta}, $meta_attr ); } # FETCH sub FIRSTKEY { my $a = scalar keys %{ $_[0]->{tblMeta} }; each %{ $_[0]->{tblMeta} }; } # FIRSTKEY sub NEXTKEY { each %{ $_[0]->{tblMeta} }; } # NEXTKEY sub EXISTS { exists $_[0]->{tblMeta}{ $_[1] }; } # EXISTS sub DELETE { croak "Can't delete single attributes from table meta structure"; } # DELETE sub CLEAR { %{ $_[0]->{tblMeta} } = (); } # CLEAR sub SCALAR { scalar %{ $_[0]->{tblMeta} }; } # SCALAR # ====== Tie-Tables ============================================================ package DBI::DBD::SqlEngine::TieTables; use Carp qw(croak); require Tie::Hash; @DBI::DBD::SqlEngine::TieTables::ISA = qw(Tie::Hash); sub TIEHASH { my ( $class, $dbh ) = @_; ( my $tbl_class = $dbh->{ImplementorClass} ) =~ s/::db$/::Table/; my $self = bless( { dbh => $dbh, tblClass => $tbl_class, }, $class ); return $self; } # new sub STORE { my ( $self, $table, $tbl_meta ) = @_; "HASH" eq ref $tbl_meta or croak "Invalid data for storing as table meta data (must be hash)"; ( undef, my $meta ) = $self->{tblClass}->get_table_meta( $self->{dbh}, $table, 1 ); $meta or croak "Invalid table name '$table'"; while ( my ( $meta_attr, $meta_val ) = each %$tbl_meta ) { $self->{tblClass}->set_table_meta_attr( $meta, $meta_attr, $meta_val ); } return; } # STORE sub FETCH { my ( $self, $table ) = @_; ( undef, my $meta ) = $self->{tblClass}->get_table_meta( $self->{dbh}, $table, 1 ); $meta or croak "Invalid table name '$table'"; my %h; tie %h, "DBI::DBD::SqlEngine::TieMeta", $self->{tblClass}, $meta; return \%h; } # FETCH sub FIRSTKEY { my $a = scalar keys %{ $_[0]->{dbh}->{sql_meta} }; each %{ $_[0]->{dbh}->{sql_meta} }; } # FIRSTKEY sub NEXTKEY { each %{ $_[0]->{dbh}->{sql_meta} }; } # NEXTKEY sub EXISTS { exists $_[0]->{dbh}->{sql_meta}->{ $_[1] } or exists $_[0]->{dbh}->{sql_meta_map}->{ $_[1] }; } # EXISTS sub DELETE { my ( $self, $table ) = @_; ( undef, my $meta ) = $self->{tblClass}->get_table_meta( $self->{dbh}, $table, 1 ); $meta or croak "Invalid table name '$table'"; delete $_[0]->{dbh}->{sql_meta}->{ $meta->{table_name} }; } # DELETE sub CLEAR { %{ $_[0]->{dbh}->{sql_meta} } = (); %{ $_[0]->{dbh}->{sql_meta_map} } = (); } # CLEAR sub SCALAR { scalar %{ $_[0]->{dbh}->{sql_meta} }; } # SCALAR # ====== STATEMENT ============================================================= package DBI::DBD::SqlEngine::st; use strict; use warnings; use vars qw(@ISA $imp_data_size); $imp_data_size = 0; sub bind_param ($$$;$) { my ( $sth, $pNum, $val, $attr ) = @_; if ( $attr && defined $val ) { my $type = ref $attr eq "HASH" ? $attr->{TYPE} : $attr; if ( $type == DBI::SQL_BIGINT() || $type == DBI::SQL_INTEGER() || $type == DBI::SQL_SMALLINT() || $type == DBI::SQL_TINYINT() ) { $val += 0; } elsif ( $type == DBI::SQL_DECIMAL() || $type == DBI::SQL_DOUBLE() || $type == DBI::SQL_FLOAT() || $type == DBI::SQL_NUMERIC() || $type == DBI::SQL_REAL() ) { $val += 0.; } else { $val = "$val"; } } $sth->{sql_params}[ $pNum - 1 ] = $val; return 1; } # bind_param sub execute { my $sth = shift; my $params = @_ ? ( $sth->{sql_params} = [@_] ) : $sth->{sql_params}; $sth->finish; my $stmt = $sth->{sql_stmt}; # must not proved when already executed - SQL::Statement modifies # received params unless ( $sth->{sql_params_checked}++ ) { # SQL::Statement and DBI::SQL::Nano will return the list of required params # when called in list context. Do not look into the several items, they're # implementation specific and may change without warning unless ( ( my $req_prm = $stmt->params() ) == ( my $nparm = @$params ) ) { my $msg = "You passed $nparm parameters where $req_prm required"; return $sth->set_err( $DBI::stderr, $msg ); } } my @err; my $result; eval { local $SIG{__WARN__} = sub { push @err, @_ }; $result = $stmt->execute( $sth, $params ); }; unless ( defined $result ) { $sth->set_err( $DBI::stderr, $@ || $stmt->{errstr} || $err[0] ); return; } if ( $stmt->{NUM_OF_FIELDS} ) { # is a SELECT statement $sth->STORE( Active => 1 ); $sth->FETCH("NUM_OF_FIELDS") or $sth->STORE( "NUM_OF_FIELDS", $stmt->{NUM_OF_FIELDS} ); } return $result; } # execute sub finish { my $sth = $_[0]; $sth->SUPER::STORE( Active => 0 ); delete $sth->{sql_stmt}{data}; return 1; } # finish sub fetch ($) { my $sth = $_[0]; my $data = $sth->{sql_stmt}{data}; if ( !$data || ref $data ne "ARRAY" ) { $sth->set_err( $DBI::stderr, "Attempt to fetch row without a preceding execute () call or from a non-SELECT statement" ); return; } my $dav = shift @$data; unless ($dav) { $sth->finish; return; } if ( $sth->FETCH("ChopBlanks") ) # XXX: (TODO) Only chop on CHAR fields, { # not on VARCHAR or NUMERIC (see DBI docs) $_ && $_ =~ s/ +$// for @$dav; } return $sth->_set_fbav($dav); } # fetch no warnings 'once'; *fetchrow_arrayref = \&fetch; use warnings; sub sql_get_colnames { my $sth = $_[0]; # Being a bit dirty here, as neither SQL::Statement::Structure nor # DBI::SQL::Nano::Statement_ does not offer an interface to the # required data my @colnames; if ( $sth->{sql_stmt}->{NAME} and "ARRAY" eq ref( $sth->{sql_stmt}->{NAME} ) ) { @colnames = @{ $sth->{sql_stmt}->{NAME} }; } elsif ( $sth->{sql_stmt}->isa('SQL::Statement') ) { my $stmt = $sth->{sql_stmt} || {}; my @coldefs = @{ $stmt->{column_defs} || [] }; @colnames = map { $_->{name} || $_->{value} } @coldefs; } @colnames = $sth->{sql_stmt}->column_names() unless (@colnames); @colnames = () if ( grep { m/\*/ } @colnames ); return @colnames; } sub FETCH ($$) { my ( $sth, $attrib ) = @_; $attrib eq "NAME" and return [ $sth->sql_get_colnames() ]; $attrib eq "TYPE" and return [ ( DBI::SQL_VARCHAR() ) x scalar $sth->sql_get_colnames() ]; $attrib eq "TYPE_NAME" and return [ ("VARCHAR") x scalar $sth->sql_get_colnames() ]; $attrib eq "PRECISION" and return [ (0) x scalar $sth->sql_get_colnames() ]; $attrib eq "NULLABLE" and return [ (1) x scalar $sth->sql_get_colnames() ]; if ( $attrib eq lc $attrib ) { # Private driver attributes are lower cased return $sth->{$attrib}; } # else pass up to DBI to handle return $sth->SUPER::FETCH($attrib); } # FETCH sub STORE ($$$) { my ( $sth, $attrib, $value ) = @_; if ( $attrib eq lc $attrib ) # Private driver attributes are lower cased { $sth->{$attrib} = $value; return 1; } return $sth->SUPER::STORE( $attrib, $value ); } # STORE sub DESTROY ($) { my $sth = shift; $sth->SUPER::FETCH("Active") and $sth->finish; undef $sth->{sql_stmt}; undef $sth->{sql_params}; } # DESTROY sub rows ($) { return $_[0]->{sql_stmt}{NUM_OF_ROWS}; } # rows # ====== TableSource =========================================================== package DBI::DBD::SqlEngine::TableSource; use strict; use warnings; use Carp; sub data_sources ($;$) { my ( $class, $drh, $attrs ) = @_; croak( ( ref( $_[0] ) ? ref( $_[0] ) : $_[0] ) . " must implement data_sources" ); } sub avail_tables { my ( $self, $dbh ) = @_; croak( ( ref( $_[0] ) ? ref( $_[0] ) : $_[0] ) . " must implement avail_tables" ); } # ====== DataSource ============================================================ package DBI::DBD::SqlEngine::DataSource; use strict; use warnings; use Carp; sub complete_table_name ($$;$) { my ( $self, $meta, $table, $respect_case ) = @_; croak( ( ref( $_[0] ) ? ref( $_[0] ) : $_[0] ) . " must implement complete_table_name" ); } sub open_data ($) { my ( $self, $meta, $attrs, $flags ) = @_; croak( ( ref( $_[0] ) ? ref( $_[0] ) : $_[0] ) . " must implement open_data" ); } # ====== SQL::STATEMENT ======================================================== package DBI::DBD::SqlEngine::Statement; use strict; use warnings; use Carp; @DBI::DBD::SqlEngine::Statement::ISA = qw(DBI::SQL::Nano::Statement); sub open_table ($$$$$) { my ( $self, $data, $table, $createMode, $lockMode ) = @_; my $class = ref $self; $class =~ s/::Statement/::Table/; my $flags = { createMode => $createMode, lockMode => $lockMode, }; $self->{command} eq "DROP" and $flags->{dropMode} = 1; my ( $tblnm, $table_meta ) = $class->get_table_meta( $data->{Database}, $table, 1 ) or croak "Cannot find appropriate meta for table '$table'"; defined $table_meta->{sql_table_class} and $class = $table_meta->{sql_table_class}; # because column name mapping is initialized in constructor ... # and therefore specific opening operations might be done before # reaching DBI::DBD::SqlEngine::Table->new(), we need to intercept # ReadOnly here my $write_op = $createMode || $lockMode || $flags->{dropMode}; if ($write_op) { $table_meta->{readonly} and croak "Table '$table' is marked readonly - " . $self->{command} . ( $lockMode ? " with locking" : "" ) . " command forbidden"; } return $class->new( $data, { table => $table }, $flags ); } # open_table # ====== SQL::TABLE ============================================================ package DBI::DBD::SqlEngine::Table; use strict; use warnings; use Carp; @DBI::DBD::SqlEngine::Table::ISA = qw(DBI::SQL::Nano::Table); sub bootstrap_table_meta { my ( $self, $dbh, $meta, $table ) = @_; defined $dbh->{ReadOnly} and !defined( $meta->{readonly} ) and $meta->{readonly} = $dbh->{ReadOnly}; defined $meta->{sql_identifier_case} or $meta->{sql_identifier_case} = $dbh->{sql_identifier_case}; exists $meta->{sql_data_source} or $meta->{sql_data_source} = $dbh->{sql_data_source}; $meta; } sub init_table_meta { my ( $self, $dbh, $meta, $table ) = @_ if (0); return; } # init_table_meta sub get_table_meta ($$$;$) { my ( $self, $dbh, $table, $respect_case, @other ) = @_; unless ( defined $respect_case ) { $respect_case = 0; $table =~ s/^\"// and $respect_case = 1; # handle quoted identifiers $table =~ s/\"$//; } unless ($respect_case) { defined $dbh->{sql_meta_map}{$table} and $table = $dbh->{sql_meta_map}{$table}; } my $meta = {}; defined $dbh->{sql_meta}{$table} and $meta = $dbh->{sql_meta}{$table}; do_initialize: unless ( $meta->{initialized} ) { $self->bootstrap_table_meta( $dbh, $meta, $table, @other ); $meta->{sql_data_source}->complete_table_name( $meta, $table, $respect_case, @other ) or return; if ( defined $meta->{table_name} and $table ne $meta->{table_name} ) { $dbh->{sql_meta_map}{$table} = $meta->{table_name}; $table = $meta->{table_name}; } # now we know a bit more - let's check if user can't use consequent spelling # XXX add know issue about reset sql_identifier_case here ... if ( defined $dbh->{sql_meta}{$table} ) { $meta = delete $dbh->{sql_meta}{$table}; # avoid endless loop $meta->{initialized} or goto do_initialize; #or $meta->{sql_data_source}->complete_table_name( $meta, $table, $respect_case, @other ) #or return; } unless ( $dbh->{sql_meta}{$table}{initialized} ) { $self->init_table_meta( $dbh, $meta, $table ); $meta->{initialized} = 1; $dbh->{sql_meta}{$table} = $meta; } } return ( $table, $meta ); } # get_table_meta my %reset_on_modify = (); my %compat_map = (); sub register_reset_on_modify { my ( $proto, $extra_resets ) = @_; foreach my $cv ( keys %$extra_resets ) { #%reset_on_modify = ( %reset_on_modify, %$extra_resets ); push @{ $reset_on_modify{$cv} }, ref $extra_resets->{$cv} ? @{ $extra_resets->{$cv} } : ( $extra_resets->{$cv} ); } return; } # register_reset_on_modify sub register_compat_map { my ( $proto, $extra_compat_map ) = @_; %compat_map = ( %compat_map, %$extra_compat_map ); return; } # register_compat_map sub get_table_meta_attr { my ( $class, $meta, $attrib ) = @_; exists $compat_map{$attrib} and $attrib = $compat_map{$attrib}; exists $meta->{$attrib} and return $meta->{$attrib}; return; } # get_table_meta_attr sub set_table_meta_attr { my ( $class, $meta, $attrib, $value ) = @_; exists $compat_map{$attrib} and $attrib = $compat_map{$attrib}; $class->table_meta_attr_changed( $meta, $attrib, $value ); $meta->{$attrib} = $value; } # set_table_meta_attr sub table_meta_attr_changed { my ( $class, $meta, $attrib, $value ) = @_; defined $reset_on_modify{$attrib} and delete @$meta{ @{ $reset_on_modify{$attrib} } } and $meta->{initialized} = 0; } # table_meta_attr_changed sub open_data { my ( $self, $meta, $attrs, $flags ) = @_; $meta->{sql_data_source} or croak "Table " . $meta->{table_name} . " not completely initialized"; $meta->{sql_data_source}->open_data( $meta, $attrs, $flags ); return; } # open_data # ====== SQL::Eval API ========================================================= sub new { my ( $className, $data, $attrs, $flags ) = @_; my $dbh = $data->{Database}; my ( $tblnm, $meta ) = $className->get_table_meta( $dbh, $attrs->{table}, 1 ) or croak "Cannot find appropriate table '$attrs->{table}'"; $attrs->{table} = $tblnm; # Being a bit dirty here, as SQL::Statement::Structure does not offer # me an interface to the data I want $flags->{createMode} && $data->{sql_stmt}{table_defs} and $meta->{table_defs} = $data->{sql_stmt}{table_defs}; # open_file must be called before inherited new is invoked # because column name mapping is initialized in constructor ... $className->open_data( $meta, $attrs, $flags ); my $tbl = { %{$attrs}, meta => $meta, col_names => $meta->{col_names} || [], }; return $className->SUPER::new($tbl); } # new sub DESTROY { my $self = shift; my $meta = $self->{meta}; $self->{row} and undef $self->{row}; () } 1; =pod =head1 NAME DBI::DBD::SqlEngine - Base class for DBI drivers without their own SQL engine =head1 SYNOPSIS package DBD::myDriver; use base qw(DBI::DBD::SqlEngine); sub driver { ... my $drh = $proto->SUPER::driver($attr); ... return $drh->{class}; } package DBD::myDriver::dr; @ISA = qw(DBI::DBD::SqlEngine::dr); sub data_sources { ... } ... package DBD::myDriver::db; @ISA = qw(DBI::DBD::SqlEngine::db); sub init_valid_attributes { ... } sub init_default_attributes { ... } sub set_versions { ... } sub validate_STORE_attr { my ($dbh, $attrib, $value) = @_; ... } sub validate_FETCH_attr { my ($dbh, $attrib) = @_; ... } sub get_myd_versions { ... } sub get_avail_tables { ... } package DBD::myDriver::st; @ISA = qw(DBI::DBD::SqlEngine::st); sub FETCH { ... } sub STORE { ... } package DBD::myDriver::Statement; @ISA = qw(DBI::DBD::SqlEngine::Statement); sub open_table { ... } package DBD::myDriver::Table; @ISA = qw(DBI::DBD::SqlEngine::Table); sub new { ... } =head1 DESCRIPTION DBI::DBD::SqlEngine abstracts the usage of SQL engines from the DBD. DBD authors can concentrate on the data retrieval they want to provide. It is strongly recommended that you read L and L, because many of the DBD::File API is provided by DBI::DBD::SqlEngine. Currently the API of DBI::DBD::SqlEngine is experimental and will likely change in the near future to provide the table meta data basics like DBD::File. DBI::DBD::SqlEngine expects that any driver in inheritance chain has a L. =head2 Metadata The following attributes are handled by DBI itself and not by DBI::DBD::SqlEngine, thus they all work as expected: Active ActiveKids CachedKids CompatMode (Not used) InactiveDestroy AutoInactiveDestroy Kids PrintError RaiseError Warn (Not used) =head3 The following DBI attributes are handled by DBI::DBD::SqlEngine: =head4 AutoCommit Always on. =head4 ChopBlanks Works. =head4 NUM_OF_FIELDS Valid after C<< $sth->execute >>. =head4 NUM_OF_PARAMS Valid after C<< $sth->prepare >>. =head4 NAME Valid after C<< $sth->execute >>; probably undef for Non-Select statements. =head4 NULLABLE Not really working, always returns an array ref of ones, as DBD::CSV does not verify input data. Valid after C<< $sth->execute >>; undef for non-select statements. =head3 The following DBI attributes and methods are not supported: =over 4 =item bind_param_inout =item CursorName =item LongReadLen =item LongTruncOk =back =head3 DBI::DBD::SqlEngine specific attributes In addition to the DBI attributes, you can use the following dbh attributes: =head4 sql_engine_version Contains the module version of this driver (B) =head4 sql_nano_version Contains the module version of DBI::SQL::Nano (B) =head4 sql_statement_version Contains the module version of SQL::Statement, if available (B) =head4 sql_handler Contains the SQL Statement engine, either DBI::SQL::Nano or SQL::Statement (B). =head4 sql_parser_object Contains an instantiated instance of SQL::Parser (B). This is filled when used first time (only when used with SQL::Statement). =head4 sql_sponge_driver Contains an internally used DBD::Sponge handle (B). =head4 sql_valid_attrs Contains the list of valid attributes for each DBI::DBD::SqlEngine based driver (B). =head4 sql_readonly_attrs Contains the list of those attributes which are readonly (B). =head4 sql_identifier_case Contains how DBI::DBD::SqlEngine deals with non-quoted SQL identifiers: * SQL_IC_UPPER (1) means all identifiers are internally converted into upper-cased pendants * SQL_IC_LOWER (2) means all identifiers are internally converted into lower-cased pendants * SQL_IC_MIXED (4) means all identifiers are taken as they are These conversions happen if (and only if) no existing identifier matches. Once existing identifier is used as known. The SQL statement execution classes doesn't have to care, so don't expect C affects column names in statements like SELECT * FROM foo =head4 sql_quoted_identifier_case Contains how DBI::DBD::SqlEngine deals with quoted SQL identifiers (B). It's fixated to SQL_IC_SENSITIVE (3), which is interpreted as SQL_IC_MIXED. =head4 sql_flags Contains additional flags to instantiate an SQL::Parser. Because an SQL::Parser is instantiated only once, it's recommended to set this flag before any statement is executed. =head4 sql_dialect Controls the dialect understood by SQL::Parser. Possible values (delivery state of SQL::Statement): * ANSI * CSV * AnyData Defaults to "CSV". Because an SQL::Parser is instantiated only once and SQL::Parser doesn't allow one to modify the dialect once instantiated, it's strongly recommended to set this flag before any statement is executed (best place is connect attribute hash). =head4 sql_engine_in_gofer This value has a true value in case of this driver is operated via L. The impact of being operated via Gofer is a read-only driver (not read-only databases!), so you cannot modify any attributes later - neither any table settings. B you won't get an error in cases you modify table attributes, so please carefully watch C. =head4 sql_meta Private data area which contains information about the tables this module handles. Table meta data might not be available until the table has been accessed for the first time e.g., by issuing a select on it however it is possible to pre-initialize attributes for each table you use. DBI::DBD::SqlEngine recognizes the (public) attributes C, C, C, C and C. Be very careful when modifying attributes you do not know, the consequence might be a destroyed or corrupted table. While C is a private and readonly attribute (which means, you cannot modify it's values), derived drivers might provide restricted write access through another attribute. Well known accessors are C for L, C for L and C for L. =head4 sql_table_source Controls the class which will be used for fetching available tables. See L for details. =head4 sql_data_source Contains the class name to be used for opening tables. See L for details. =head2 Driver private methods =head3 Default DBI methods =head4 data_sources The C method returns a list of subdirectories of the current directory in the form "dbi:CSV:f_dir=$dirname". If you want to read the subdirectories of another directory, use my ($drh) = DBI->install_driver ("CSV"); my (@list) = $drh->data_sources (f_dir => "/usr/local/csv_data"); =head4 list_tables This method returns a list of file names inside $dbh->{f_dir}. Example: my ($dbh) = DBI->connect ("dbi:CSV:f_dir=/usr/local/csv_data"); my (@list) = $dbh->func ("list_tables"); Note that the list includes all files contained in the directory, even those that have non-valid table names, from the view of SQL. =head3 Additional methods The following methods are only available via their documented name when DBI::DBD::SQlEngine is used directly. Because this is only reasonable for testing purposes, the real names must be used instead. Those names can be computed by replacing the C in the method name with the driver prefix. =head4 sql_versions Signature: sub sql_versions (;$) { my ($table_name) = @_; $table_name ||= "."; ... } Returns the versions of the driver, including the DBI version, the Perl version, DBI::PurePerl version (if DBI::PurePerl is active) and the version of the SQL engine in use. my $dbh = DBI->connect ("dbi:File:"); my $sql_versions = $dbh->func( "sql_versions" ); print "$sql_versions\n"; __END__ # DBI::DBD::SqlEngine 0.05 using SQL::Statement 1.402 # DBI 1.623 # OS netbsd (6.99.12) # Perl 5.016002 (x86_64-netbsd-thread-multi) Called in list context, sql_versions will return an array containing each line as single entry. Some drivers might use the optional (table name) argument and modify version information related to the table (e.g. DBD::DBM provides storage backend information for the requested table, when it has a table name). =head4 sql_get_meta Signature: sub sql_get_meta ($$) { my ($table_name, $attrib) = @_; ... } Returns the value of a meta attribute set for a specific table, if any. See L for the possible attributes. A table name of C<"."> (single dot) is interpreted as the default table. This will retrieve the appropriate attribute globally from the dbh. This has the same restrictions as C<< $dbh->{$attrib} >>. =head4 sql_set_meta Signature: sub sql_set_meta ($$$) { my ($table_name, $attrib, $value) = @_; ... } Sets the value of a meta attribute set for a specific table. See L for the possible attributes. A table name of C<"."> (single dot) is interpreted as the default table which will set the specified attribute globally for the dbh. This has the same restrictions as C<< $dbh->{$attrib} = $value >>. =head4 sql_clear_meta Signature: sub sql_clear_meta ($) { my ($table_name) = @_; ... } Clears the table specific meta information in the private storage of the dbh. =head2 Extensibility =head3 DBI::DBD::SqlEngine::TableSource Provides data sources and table information on database driver and database handle level. package DBI::DBD::SqlEngine::TableSource; sub data_sources ($;$) { my ( $class, $drh, $attrs ) = @_; ... } sub avail_tables { my ( $class, $drh ) = @_; ... } The C method is called when the user invokes any of the following: @ary = DBI->data_sources($driver); @ary = DBI->data_sources($driver, \%attr); @ary = $dbh->data_sources(); @ary = $dbh->data_sources(\%attr); The C method is called when the user invokes any of the following: @names = $dbh->tables( $catalog, $schema, $table, $type ); $sth = $dbh->table_info( $catalog, $schema, $table, $type ); $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr ); $dbh->func( "list_tables" ); Every time where an C<\%attr> argument can be specified, this C<\%attr> object's C attribute is preferred over the C<$dbh> attribute or the driver default, eg. @ary = DBI->data_sources("dbi:CSV:", { f_dir => "/your/csv/tables", # note: this class doesn't comes with DBI sql_table_source => "DBD::File::Archive::Tar::TableSource", # scan tarballs instead of directories }); When you're going to implement such a DBD::File::Archive::Tar::TableSource class, remember to add correct attributes (including C and C) to the returned DSN's. =head3 DBI::DBD::SqlEngine::DataSource Provides base functionality for dealing with tables. It is primarily designed for allowing transparent access to files on disk or already opened (file-)streams (eg. for DBD::CSV). Derived classes shall be restricted to similar functionality, too (eg. opening streams from an archive, transparently compress/uncompress log files before parsing them, package DBI::DBD::SqlEngine::DataSource; sub complete_table_name ($$;$) { my ( $self, $meta, $table, $respect_case ) = @_; ... } The method C is called when first setting up the I for a table: "SELECT user.id, user.name, user.shell FROM user WHERE ..." results in opening the table C. First step of the table open process is completing the name. Let's imagine you're having a L handle with following settings: $dbh->{sql_identifier_case} = SQL_IC_LOWER; $dbh->{f_ext} = '.lst'; $dbh->{f_dir} = '/data/web/adrmgr'; Those settings will result in looking for files matching C<[Uu][Ss][Ee][Rr](\.lst)?$> in C. The scanning of the directory C and the pattern match check will be done in C by the C method. If you intend to provide other sources of data streams than files, in addition to provide an appropriate C method, a method to open the resource is required: package DBI::DBD::SqlEngine::DataSource; sub open_data ($) { my ( $self, $meta, $attrs, $flags ) = @_; ... } After the method C has been run successfully, the table's meta information are in a state which allowes the table's data accessor methods will be able to fetch/store row information. Implementation details heavily depends on the table implementation, whereby the most famous is surely L. =head1 SQL ENGINES DBI::DBD::SqlEngine currently supports two SQL engines: L and L. DBI::SQL::Nano supports a I limited subset of SQL statements, but it might be faster for some very simple tasks. SQL::Statement in contrast supports a much larger subset of ANSI SQL. To use SQL::Statement, you need at least version 1.401 of SQL::Statement and the environment variable C must not be set to a true value. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc DBI::DBD::SqlEngine You can also look for information at: =over 4 =item * RT: CPAN's request tracker L L =item * AnnoCPAN: Annotated CPAN documentation L L =item * CPAN Ratings L =item * Search CPAN L =back =head2 Where can I go for more help? For questions about installation or usage, please ask on the dbi-dev@perl.org mailing list. If you have a bug report, patch or suggestion, please open a new report ticket on CPAN, if there is not already one for the issue you want to report. Of course, you can mail any of the module maintainers, but it is less likely to be missed if it is reported on RT. Report tickets should contain a detailed description of the bug or enhancement request you want to report and at least an easy way to verify/reproduce the issue and any supplied fix. Patches are always welcome, too. =head1 ACKNOWLEDGEMENTS Thanks to Tim Bunce, Martin Evans and H.Merijn Brand for their continued support while developing DBD::File, DBD::DBM and DBD::AnyData. Their support, hints and feedback helped to design and implement this module. =head1 AUTHOR This module is currently maintained by H.Merijn Brand < h.m.brand at xs4all.nl > and Jens Rehsack < rehsack at googlemail.com > The original authors are Jochen Wiedmann and Jeff Zucker. =head1 COPYRIGHT AND LICENSE Copyright (C) 2009-2013 by H.Merijn Brand & Jens Rehsack Copyright (C) 2004-2009 by Jeff Zucker Copyright (C) 1998-2004 by Jochen Wiedmann All rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =head1 SEE ALSO L, L, L and L. =cut PK1])bS99File.pmnu[# -*- perl -*- # # DBD::File - A base class for implementing DBI drivers that # act on plain files # # This module is currently maintained by # # H.Merijn Brand & Jens Rehsack # # The original author is Jochen Wiedmann. # # Copyright (C) 2009-2013 by H.Merijn Brand & Jens Rehsack # Copyright (C) 2004 by Jeff Zucker # Copyright (C) 1998 by Jochen Wiedmann # # All rights reserved. # # You may distribute this module under the terms of either the GNU # General Public License or the Artistic License, as specified in # the Perl README file. require 5.008; use strict; use warnings; use DBI (); package DBD::File; use strict; use warnings; use base qw( DBI::DBD::SqlEngine ); use Carp; use vars qw( @ISA $VERSION $drh ); $VERSION = "0.44"; $drh = undef; # holds driver handle(s) once initialized sub driver ($;$) { my ($class, $attr) = @_; # Drivers typically use a singleton object for the $drh # We use a hash here to have one singleton per subclass. # (Otherwise DBD::CSV and DBD::DBM, for example, would # share the same driver object which would cause problems.) # An alternative would be to not cache the $drh here at all # and require that subclasses do that. Subclasses should do # their own caching, so caching here just provides extra safety. $drh->{$class} and return $drh->{$class}; $attr ||= {}; { no strict "refs"; unless ($attr->{Attribution}) { $class eq "DBD::File" and $attr->{Attribution} = "$class by Jeff Zucker"; $attr->{Attribution} ||= ${$class . "::ATTRIBUTION"} || "oops the author of $class forgot to define this"; } $attr->{Version} ||= ${$class . "::VERSION"}; $attr->{Name} or ($attr->{Name} = $class) =~ s/^DBD\:\://; } $drh->{$class} = $class->SUPER::driver ($attr); # XXX inject DBD::XXX::Statement unless exists return $drh->{$class}; } # driver sub CLONE { undef $drh; } # CLONE # ====== DRIVER ================================================================ package DBD::File::dr; use strict; use warnings; use vars qw( @ISA $imp_data_size ); use Carp; @DBD::File::dr::ISA = qw( DBI::DBD::SqlEngine::dr ); $DBD::File::dr::imp_data_size = 0; sub dsn_quote { my $str = shift; ref $str and return ""; defined $str or return ""; $str =~ s/([;:\\])/\\$1/g; return $str; } # dsn_quote # XXX rewrite using TableConfig ... sub default_table_source { "DBD::File::TableSource::FileSystem" } sub connect { my ($drh, $dbname, $user, $auth, $attr) = @_; # We do not (yet) care about conflicting attributes here # my $dbh = DBI->connect ("dbi:CSV:f_dir=test", undef, undef, { f_dir => "text" }); # will test here that both test and text should exist if (my $attr_hash = (DBI->parse_dsn ($dbname))[3]) { if (defined $attr_hash->{f_dir} && ! -d $attr_hash->{f_dir}) { my $msg = "No such directory '$attr_hash->{f_dir}"; $drh->set_err (2, $msg); $attr_hash->{RaiseError} and croak $msg; return; } } if ($attr and defined $attr->{f_dir} && ! -d $attr->{f_dir}) { my $msg = "No such directory '$attr->{f_dir}"; $drh->set_err (2, $msg); $attr->{RaiseError} and croak $msg; return; } return $drh->SUPER::connect ($dbname, $user, $auth, $attr); } # connect sub disconnect_all { } # disconnect_all sub DESTROY { undef; } # DESTROY # ====== DATABASE ============================================================== package DBD::File::db; use strict; use warnings; use vars qw( @ISA $imp_data_size ); use Carp; require File::Spec; require Cwd; use Scalar::Util qw( refaddr ); # in CORE since 5.7.3 @DBD::File::db::ISA = qw( DBI::DBD::SqlEngine::db ); $DBD::File::db::imp_data_size = 0; sub data_sources { my ($dbh, $attr, @other) = @_; ref ($attr) eq "HASH" or $attr = {}; exists $attr->{f_dir} or $attr->{f_dir} = $dbh->{f_dir}; exists $attr->{f_dir_search} or $attr->{f_dir_search} = $dbh->{f_dir_search}; return $dbh->SUPER::data_sources ($attr, @other); } # data_source sub set_versions { my $dbh = shift; $dbh->{f_version} = $DBD::File::VERSION; return $dbh->SUPER::set_versions (); } # set_versions sub init_valid_attributes { my $dbh = shift; $dbh->{f_valid_attrs} = { f_version => 1, # DBD::File version f_dir => 1, # base directory f_dir_search => 1, # extended search directories f_ext => 1, # file extension f_schema => 1, # schema name f_lock => 1, # Table locking mode f_lockfile => 1, # Table lockfile extension f_encoding => 1, # Encoding of the file f_valid_attrs => 1, # File valid attributes f_readonly_attrs => 1, # File readonly attributes }; $dbh->{f_readonly_attrs} = { f_version => 1, # DBD::File version f_valid_attrs => 1, # File valid attributes f_readonly_attrs => 1, # File readonly attributes }; return $dbh->SUPER::init_valid_attributes (); } # init_valid_attributes sub init_default_attributes { my ($dbh, $phase) = @_; # must be done first, because setting flags implicitly calls $dbdname::db->STORE $dbh->SUPER::init_default_attributes ($phase); # DBI::BD::SqlEngine::dr::connect will detect old-style drivers and # don't call twice unless (defined $phase) { # we have an "old" driver here $phase = defined $dbh->{sql_init_phase}; $phase and $phase = $dbh->{sql_init_phase}; } if (0 == $phase) { # f_ext should not be initialized # f_map is deprecated (but might return) $dbh->{f_dir} = Cwd::abs_path (File::Spec->curdir ()); push @{$dbh->{sql_init_order}{90}}, "f_meta"; # complete derived attributes, if required (my $drv_class = $dbh->{ImplementorClass}) =~ s/::db$//; my $drv_prefix = DBI->driver_prefix ($drv_class); if (exists $dbh->{$drv_prefix . "meta"} and !$dbh->{sql_engine_in_gofer}) { my $attr = $dbh->{$drv_prefix . "meta"}; defined $dbh->{f_valid_attrs}{f_meta} and $dbh->{f_valid_attrs}{f_meta} = 1; $dbh->{f_meta} = $dbh->{$attr}; } } return $dbh; } # init_default_attributes sub validate_FETCH_attr { my ($dbh, $attrib) = @_; $attrib eq "f_meta" and $dbh->{sql_engine_in_gofer} and $attrib = "sql_meta"; return $dbh->SUPER::validate_FETCH_attr ($attrib); } # validate_FETCH_attr sub validate_STORE_attr { my ($dbh, $attrib, $value) = @_; if ($attrib eq "f_dir" && defined $value) { -d $value or return $dbh->set_err ($DBI::stderr, "No such directory '$value'"); File::Spec->file_name_is_absolute ($value) or $value = Cwd::abs_path ($value); } if ($attrib eq "f_ext") { $value eq "" || $value =~ m{^\.\w+(?:/[rR]*)?$} or carp "'$value' doesn't look like a valid file extension attribute\n"; } $attrib eq "f_meta" and $dbh->{sql_engine_in_gofer} and $attrib = "sql_meta"; return $dbh->SUPER::validate_STORE_attr ($attrib, $value); } # validate_STORE_attr sub get_f_versions { my ($dbh, $table) = @_; my $class = $dbh->{ImplementorClass}; $class =~ s/::db$/::Table/; my $dver; my $dtype = "IO::File"; eval { $dver = IO::File->VERSION (); # when we're still alive here, everything went ok - no need to check for $@ $dtype .= " ($dver)"; }; my $f_encoding; if ($table) { my $meta; $table and (undef, $meta) = $class->get_table_meta ($dbh, $table, 1); $meta and $meta->{f_encoding} and $f_encoding = $meta->{f_encoding}; } # if ($table) $f_encoding ||= $dbh->{f_encoding}; $f_encoding and $dtype .= " + " . $f_encoding . " encoding"; return sprintf "%s using %s", $dbh->{f_version}, $dtype; } # get_f_versions # ====== STATEMENT ============================================================= package DBD::File::st; use strict; use warnings; use vars qw( @ISA $imp_data_size ); @DBD::File::st::ISA = qw( DBI::DBD::SqlEngine::st ); $DBD::File::st::imp_data_size = 0; my %supported_attrs = ( TYPE => 1, PRECISION => 1, NULLABLE => 1, ); sub FETCH { my ($sth, $attr) = @_; if ($supported_attrs{$attr}) { my $stmt = $sth->{sql_stmt}; if (exists $sth->{ImplementorClass} && exists $sth->{sql_stmt} && $sth->{sql_stmt}->isa ("SQL::Statement")) { # fill overall_defs unless we know unless (exists $sth->{f_overall_defs} && ref $sth->{f_overall_defs}) { my $types = $sth->{Database}{Types}; unless ($types) { # Fetch types only once per database if (my $t = $sth->{Database}->type_info_all ()) { foreach my $i (1 .. $#$t) { $types->{uc $t->[$i][0]} = $t->[$i][1]; $types->{$t->[$i][1]} ||= uc $t->[$i][0]; } } # sane defaults for ([ 0, "" ], [ 1, "CHAR" ], [ 4, "INTEGER" ], [ 12, "VARCHAR" ], ) { $types->{$_->[0]} ||= $_->[1]; $types->{$_->[1]} ||= $_->[0]; } $sth->{Database}{Types} = $types; } my $all_meta = $sth->{Database}->func ("*", "table_defs", "get_sql_engine_meta"); foreach my $tbl (keys %$all_meta) { my $meta = $all_meta->{$tbl}; exists $meta->{table_defs} && ref $meta->{table_defs} or next; foreach (keys %{$meta->{table_defs}{columns}}) { my $field_info = $meta->{table_defs}{columns}{$_}; if (defined $field_info->{data_type} && $field_info->{data_type} !~ m/^[0-9]+$/) { $field_info->{type_name} = uc $field_info->{data_type}; $field_info->{data_type} = $types->{$field_info->{type_name}} || 0; } $field_info->{type_name} ||= $types->{$field_info->{data_type}} || "CHAR"; $sth->{f_overall_defs}{$_} = $field_info; } } } my @colnames = $sth->sql_get_colnames (); $attr eq "TYPE" and return [ map { $sth->{f_overall_defs}{$_}{data_type} || 12 } @colnames ]; $attr eq "TYPE_NAME" and return [ map { $sth->{f_overall_defs}{$_}{type_name} || "VARCHAR" } @colnames ]; $attr eq "PRECISION" and return [ map { $sth->{f_overall_defs}{$_}{data_length} || 0 } @colnames ]; $attr eq "NULLABLE" and return [ map { ( grep { $_ eq "NOT NULL" } @{ $sth->{f_overall_defs}{$_}{constraints} || [] }) ? 0 : 1 } @colnames ]; } } return $sth->SUPER::FETCH ($attr); } # FETCH # ====== TableSource =========================================================== package DBD::File::TableSource::FileSystem; use strict; use warnings; use IO::Dir; @DBD::File::TableSource::FileSystem::ISA = "DBI::DBD::SqlEngine::TableSource"; sub data_sources { my ($class, $drh, $attr) = @_; my $dir = $attr && exists $attr->{f_dir} ? $attr->{f_dir} : File::Spec->curdir (); defined $dir or return; # Stream-based databases do not have f_dir unless (-d $dir && -r $dir && -x $dir) { $drh->set_err ($DBI::stderr, "Cannot use directory $dir from f_dir"); return; } my %attrs; $attr and %attrs = %$attr; delete $attrs{f_dir}; my $dsn_quote = $drh->{ImplementorClass}->can ("dsn_quote"); my $dsnextra = join ";", map { $_ . "=" . &{$dsn_quote} ($attrs{$_}) } keys %attrs; my @dir = ($dir); $attr->{f_dir_search} && ref $attr->{f_dir_search} eq "ARRAY" and push @dir, grep { -d $_ } @{$attr->{f_dir_search}}; my @dsns; foreach $dir (@dir) { my $dirh = IO::Dir->new ($dir); unless (defined $dirh) { $drh->set_err ($DBI::stderr, "Cannot open directory $dir: $!"); return; } my ($file, %names, $driver); $driver = $drh->{ImplementorClass} =~ m/^dbd\:\:([^\:]+)\:\:/i ? $1 : "File"; while (defined ($file = $dirh->read ())) { my $d = File::Spec->catdir ($dir, $file); # allow current dir ... it can be a data_source too $file ne File::Spec->updir () && -d $d and push @dsns, "DBI:$driver:f_dir=" . &{$dsn_quote} ($d) . ($dsnextra ? ";$dsnextra" : ""); } } return @dsns; } # data_sources sub avail_tables { my ($self, $dbh) = @_; my $dir = $dbh->{f_dir}; defined $dir or return; # Stream based db's cannot be queried for tables my %seen; my @tables; my @dir = ($dir); $dbh->{f_dir_search} && ref $dbh->{f_dir_search} eq "ARRAY" and push @dir, grep { -d $_ } @{$dbh->{f_dir_search}}; foreach $dir (@dir) { my $dirh = IO::Dir->new ($dir); unless (defined $dirh) { $dbh->set_err ($DBI::stderr, "Cannot open directory $dir: $!"); return; } my $class = $dbh->FETCH ("ImplementorClass"); $class =~ s/::db$/::Table/; my ($file, %names); my $schema = exists $dbh->{f_schema} ? defined $dbh->{f_schema} && $dbh->{f_schema} ne "" ? $dbh->{f_schema} : undef : eval { getpwuid ((stat $dir)[4]) }; # XXX Win32::pwent while (defined ($file = $dirh->read ())) { my ($tbl, $meta) = $class->get_table_meta ($dbh, $file, 0, 0) or next; # XXX # $tbl && $meta && -f $meta->{f_fqfn} or next; $seen{defined $schema ? $schema : "\0"}{$dir}{$tbl}++ or push @tables, [ undef, $schema, $tbl, "TABLE", "FILE" ]; } $dirh->close () or $dbh->set_err ($DBI::stderr, "Cannot close directory $dir: $!"); } return @tables; } # avail_tables # ====== DataSource ============================================================ package DBD::File::DataSource::Stream; use strict; use warnings; use Carp; @DBD::File::DataSource::Stream::ISA = "DBI::DBD::SqlEngine::DataSource"; # We may have a working flock () built-in but that doesn't mean that locking # will work on NFS (flock () may hang hard) my $locking = eval { my $fh; my $nulldevice = File::Spec->devnull (); open $fh, ">", $nulldevice or croak "Can't open $nulldevice: $!"; flock $fh, 0; close $fh; 1; }; sub complete_table_name { my ($self, $meta, $file, $respect_case) = @_; my $tbl = $file; if (!$respect_case and $meta->{sql_identifier_case} == 1) { # XXX SQL_IC_UPPER $tbl = uc $tbl; } elsif (!$respect_case and $meta->{sql_identifier_case} == 2) { # XXX SQL_IC_LOWER $tbl = lc $tbl; } $meta->{f_fqfn} = undef; $meta->{f_fqbn} = undef; $meta->{f_fqln} = undef; $meta->{table_name} = $tbl; return $tbl; } # complete_table_name sub apply_encoding { my ($self, $meta, $fn) = @_; defined $fn or $fn = "file handle " . fileno ($meta->{fh}); if (my $enc = $meta->{f_encoding}) { binmode $meta->{fh}, ":encoding($enc)" or croak "Failed to set encoding layer '$enc' on $fn: $!"; } else { binmode $meta->{fh} or croak "Failed to set binary mode on $fn: $!"; } } # apply_encoding sub open_data { my ($self, $meta, $attrs, $flags) = @_; $flags->{dropMode} and croak "Can't drop a table in stream"; my $fn = "file handle " . fileno ($meta->{f_file}); if ($flags->{createMode} || $flags->{lockMode}) { $meta->{fh} = IO::Handle->new_from_fd (fileno ($meta->{f_file}), "w+") or croak "Cannot open $fn for writing: $! (" . ($!+0) . ")"; } else { $meta->{fh} = IO::Handle->new_from_fd (fileno ($meta->{f_file}), "r") or croak "Cannot open $fn for reading: $! (" . ($!+0) . ")"; } if ($meta->{fh}) { $self->apply_encoding ($meta, $fn); } # have $meta->{$fh} if ($self->can_flock && $meta->{fh}) { my $lm = defined $flags->{f_lock} && $flags->{f_lock} =~ m/^[012]$/ ? $flags->{f_lock} : $flags->{lockMode} ? 2 : 1; if ($lm == 2) { flock $meta->{fh}, 2 or croak "Cannot obtain exclusive lock on $fn: $!"; } elsif ($lm == 1) { flock $meta->{fh}, 1 or croak "Cannot obtain shared lock on $fn: $!"; } # $lm = 0 is forced no locking at all } } # open_data sub can_flock { $locking } package DBD::File::DataSource::File; use strict; use warnings; @DBD::File::DataSource::File::ISA = "DBD::File::DataSource::Stream"; use Carp; my $fn_any_ext_regex = qr/\.[^.]*/; sub complete_table_name { my ($self, $meta, $file, $respect_case, $file_is_table) = @_; $file eq "." || $file eq ".." and return; # XXX would break a possible DBD::Dir # XXX now called without proving f_fqfn first ... my ($ext, $req) = ("", 0); if ($meta->{f_ext}) { ($ext, my $opt) = split m{/}, $meta->{f_ext}; if ($ext && $opt) { $opt =~ m/r/i and $req = 1; } } # (my $tbl = $file) =~ s/\Q$ext\E$//i; my ($tbl, $basename, $dir, $fn_ext, $user_spec_file, $searchdir); if ($file_is_table and defined $meta->{f_file}) { $tbl = $file; ($basename, $dir, $fn_ext) = File::Basename::fileparse ($meta->{f_file}, $fn_any_ext_regex); $file = $basename . $fn_ext; $user_spec_file = 1; } else { ($basename, $dir, undef) = File::Basename::fileparse ($file, qr{\Q$ext\E}); # $dir is returned with trailing (back)slash. We just need to check # if it is ".", "./", or ".\" or "[]" (VMS) if ($dir =~ m{^(?:[.][/\\]?|\[\])$} && ref $meta->{f_dir_search} eq "ARRAY") { foreach my $d ($meta->{f_dir}, @{$meta->{f_dir_search}}) { my $f = File::Spec->catdir ($d, $file); -f $f or next; $searchdir = Cwd::abs_path ($d); $dir = ""; last; } } $file = $tbl = $basename; $user_spec_file = 0; } if (!$respect_case and $meta->{sql_identifier_case} == 1) { # XXX SQL_IC_UPPER $basename = uc $basename; $tbl = uc $tbl; } elsif (!$respect_case and $meta->{sql_identifier_case} == 2) { # XXX SQL_IC_LOWER $basename = lc $basename; $tbl = lc $tbl; } unless (defined $searchdir) { $searchdir = File::Spec->file_name_is_absolute ($dir) ? ($dir =~ s{/$}{}, $dir) : Cwd::abs_path (File::Spec->catdir ($meta->{f_dir}, $dir)); } -d $searchdir or croak "-d $searchdir: $!"; $searchdir eq $meta->{f_dir} and $dir = ""; unless ($user_spec_file) { $file_is_table and $file = "$basename$ext"; # Fully Qualified File Name my $cmpsub; if ($respect_case) { $cmpsub = sub { my ($fn, undef, $sfx) = File::Basename::fileparse ($_, $fn_any_ext_regex); $^O eq "VMS" && $sfx eq "." and $sfx = ""; # no extension turns up as a dot $fn eq $basename and return (lc $sfx eq lc $ext or !$req && !$sfx); return 0; } } else { $cmpsub = sub { my ($fn, undef, $sfx) = File::Basename::fileparse ($_, $fn_any_ext_regex); $^O eq "VMS" && $sfx eq "." and $sfx = ""; # no extension turns up as a dot lc $fn eq lc $basename and return (lc $sfx eq lc $ext or !$req && !$sfx); return 0; } } my @f; { my $dh = IO::Dir->new ($searchdir) or croak "Can't open '$searchdir': $!"; @f = sort { length $b <=> length $a } grep { &$cmpsub ($_) } $dh->read (); $dh->close () or croak "Can't close '$searchdir': $!"; } @f > 0 && @f <= 2 and $file = $f[0]; !$respect_case && $meta->{sql_identifier_case} == 4 and # XXX SQL_IC_MIXED ($tbl = $file) =~ s/\Q$ext\E$//i; my $tmpfn = $file; if ($ext && $req) { # File extension required $tmpfn =~ s/\Q$ext\E$//i or return; } } my $fqfn = File::Spec->catfile ($searchdir, $file); my $fqbn = File::Spec->catfile ($searchdir, $basename); $meta->{f_fqfn} = $fqfn; $meta->{f_fqbn} = $fqbn; defined $meta->{f_lockfile} && $meta->{f_lockfile} and $meta->{f_fqln} = $meta->{f_fqbn} . $meta->{f_lockfile}; $dir && !$user_spec_file and $tbl = File::Spec->catfile ($dir, $tbl); $meta->{table_name} = $tbl; return $tbl; } # complete_table_name sub open_data { my ($self, $meta, $attrs, $flags) = @_; defined $meta->{f_fqfn} && $meta->{f_fqfn} ne "" or croak "No filename given"; my ($fh, $fn); unless ($meta->{f_dontopen}) { $fn = $meta->{f_fqfn}; if ($flags->{createMode}) { -f $meta->{f_fqfn} and croak "Cannot create table $attrs->{table}: Already exists"; $fh = IO::File->new ($fn, "a+") or croak "Cannot open $fn for writing: $! (" . ($!+0) . ")"; } else { unless ($fh = IO::File->new ($fn, ($flags->{lockMode} ? "r+" : "r"))) { croak "Cannot open $fn: $! (" . ($!+0) . ")"; } } $meta->{fh} = $fh; if ($fh) { $fh->seek (0, 0) or croak "Error while seeking back: $!"; $self->apply_encoding ($meta); } } if ($meta->{f_fqln}) { $fn = $meta->{f_fqln}; if ($flags->{createMode}) { -f $fn and croak "Cannot create table lock at '$fn' for $attrs->{table}: Already exists"; $fh = IO::File->new ($fn, "a+") or croak "Cannot open $fn for writing: $! (" . ($!+0) . ")"; } else { unless ($fh = IO::File->new ($fn, ($flags->{lockMode} ? "r+" : "r"))) { croak "Cannot open $fn: $! (" . ($!+0) . ")"; } } $meta->{lockfh} = $fh; } if ($self->can_flock && $fh) { my $lm = defined $flags->{f_lock} && $flags->{f_lock} =~ m/^[012]$/ ? $flags->{f_lock} : $flags->{lockMode} ? 2 : 1; if ($lm == 2) { flock $fh, 2 or croak "Cannot obtain exclusive lock on $fn: $!"; } elsif ($lm == 1) { flock $fh, 1 or croak "Cannot obtain shared lock on $fn: $!"; } # $lm = 0 is forced no locking at all } } # open_data # ====== SQL::STATEMENT ======================================================== package DBD::File::Statement; use strict; use warnings; @DBD::File::Statement::ISA = qw( DBI::DBD::SqlEngine::Statement ); # ====== SQL::TABLE ============================================================ package DBD::File::Table; use strict; use warnings; use Carp; require IO::File; require File::Basename; require File::Spec; require Cwd; require Scalar::Util; @DBD::File::Table::ISA = qw( DBI::DBD::SqlEngine::Table ); # ====== UTILITIES ============================================================ if (eval { require Params::Util; }) { Params::Util->import ("_HANDLE"); } else { # taken but modified from Params::Util ... *_HANDLE = sub { # It has to be defined, of course defined $_[0] or return; # Normal globs are considered to be file handles ref $_[0] eq "GLOB" and return $_[0]; # Check for a normal tied filehandle # Side Note: 5.5.4's tied () and can () doesn't like getting undef tied ($_[0]) and tied ($_[0])->can ("TIEHANDLE") and return $_[0]; # There are no other non-object handles that we support Scalar::Util::blessed ($_[0]) or return; # Check for a common base classes for conventional IO::Handle object $_[0]->isa ("IO::Handle") and return $_[0]; # Check for tied file handles using Tie::Handle $_[0]->isa ("Tie::Handle") and return $_[0]; # IO::Scalar is not a proper seekable, but it is valid is a # regular file handle $_[0]->isa ("IO::Scalar") and return $_[0]; # Yet another special case for IO::String, which refuses (for now # anyway) to become a subclass of IO::Handle. $_[0]->isa ("IO::String") and return $_[0]; # This is not any sort of object we know about return; }; } # ====== FLYWEIGHT SUPPORT ===================================================== # Flyweight support for table_info # The functions file2table, init_table_meta, default_table_meta and # get_table_meta are using $self arguments for polymorphism only. The # must not rely on an instantiated DBD::File::Table sub file2table { my ($self, $meta, $file, $file_is_table, $respect_case) = @_; return $meta->{sql_data_source}->complete_table_name ($meta, $file, $respect_case, $file_is_table); } # file2table sub bootstrap_table_meta { my ($self, $dbh, $meta, $table, @other) = @_; $self->SUPER::bootstrap_table_meta ($dbh, $meta, $table, @other); exists $meta->{f_dir} or $meta->{f_dir} = $dbh->{f_dir}; exists $meta->{f_dir_search} or $meta->{f_dir_search} = $dbh->{f_dir_search}; defined $meta->{f_ext} or $meta->{f_ext} = $dbh->{f_ext}; defined $meta->{f_encoding} or $meta->{f_encoding} = $dbh->{f_encoding}; exists $meta->{f_lock} or $meta->{f_lock} = $dbh->{f_lock}; exists $meta->{f_lockfile} or $meta->{f_lockfile} = $dbh->{f_lockfile}; defined $meta->{f_schema} or $meta->{f_schema} = $dbh->{f_schema}; defined $meta->{f_open_file_needed} or $meta->{f_open_file_needed} = $self->can ("open_file") != DBD::File::Table->can ("open_file"); defined ($meta->{sql_data_source}) or $meta->{sql_data_source} = _HANDLE ($meta->{f_file}) ? "DBD::File::DataSource::Stream" : "DBD::File::DataSource::File"; } # bootstrap_table_meta sub get_table_meta ($$$$;$) { my ($self, $dbh, $table, $file_is_table, $respect_case) = @_; my $meta = $self->SUPER::get_table_meta ($dbh, $table, $respect_case, $file_is_table); $table = $meta->{table_name}; return unless $table; return ($table, $meta); } # get_table_meta my %reset_on_modify = ( f_file => [ "f_fqfn", "sql_data_source" ], f_dir => "f_fqfn", f_dir_search => [], f_ext => "f_fqfn", f_lockfile => "f_fqfn", # forces new file2table call ); __PACKAGE__->register_reset_on_modify (\%reset_on_modify); my %compat_map = map { $_ => "f_$_" } qw( file ext lock lockfile ); __PACKAGE__->register_compat_map (\%compat_map); # ====== DBD::File <= 0.40 compat stuff ======================================== # compat to 0.38 .. 0.40 API sub open_file { my ($className, $meta, $attrs, $flags) = @_; return $className->SUPER::open_data ($meta, $attrs, $flags); } # open_file sub open_data { my ($className, $meta, $attrs, $flags) = @_; # compat to 0.38 .. 0.40 API $meta->{f_open_file_needed} ? $className->open_file ($meta, $attrs, $flags) : $className->SUPER::open_data ($meta, $attrs, $flags); return; } # open_data # ====== SQL::Eval API ========================================================= sub drop ($) { my ($self, $data) = @_; my $meta = $self->{meta}; # We have to close the file before unlinking it: Some OS'es will # refuse the unlink otherwise. $meta->{fh} and $meta->{fh}->close (); $meta->{lockfh} and $meta->{lockfh}->close (); undef $meta->{fh}; undef $meta->{lockfh}; $meta->{f_fqfn} and unlink $meta->{f_fqfn}; # XXX ==> sql_data_source $meta->{f_fqln} and unlink $meta->{f_fqln}; # XXX ==> sql_data_source delete $data->{Database}{sql_meta}{$self->{table}}; return 1; } # drop sub seek ($$$$) { my ($self, $data, $pos, $whence) = @_; my $meta = $self->{meta}; if ($whence == 0 && $pos == 0) { $pos = defined $meta->{first_row_pos} ? $meta->{first_row_pos} : 0; } elsif ($whence != 2 || $pos != 0) { croak "Illegal seek position: pos = $pos, whence = $whence"; } $meta->{fh}->seek ($pos, $whence) or croak "Error while seeking in " . $meta->{f_fqfn} . ": $!"; } # seek sub truncate ($$) { my ($self, $data) = @_; my $meta = $self->{meta}; $meta->{fh}->truncate ($meta->{fh}->tell ()) or croak "Error while truncating " . $meta->{f_fqfn} . ": $!"; return 1; } # truncate sub DESTROY { my $self = shift; my $meta = $self->{meta}; $meta->{fh} and $meta->{fh}->close (); $meta->{lockfh} and $meta->{lockfh}->close (); undef $meta->{fh}; undef $meta->{lockfh}; $self->SUPER::DESTROY(); } # DESTROY 1; __END__ =head1 NAME DBD::File - Base class for writing file based DBI drivers =head1 SYNOPSIS This module is a base class for writing other Ls. It is not intended to function as a DBD itself (though it is possible). If you want to access flat files, use L, or L (both of which are subclasses of DBD::File). =head1 DESCRIPTION The DBD::File module is not a true L driver, but an abstract base class for deriving concrete DBI drivers from it. The implication is, that these drivers work with plain files, for example CSV files or INI files. The module is based on the L module, a simple SQL engine. See L for details on DBI, L for details on SQL::Statement and L, L or L for example drivers. =head2 Metadata The following attributes are handled by DBI itself and not by DBD::File, thus they all work as expected: Active ActiveKids CachedKids CompatMode (Not used) InactiveDestroy AutoInactiveDestroy Kids PrintError RaiseError Warn (Not used) =head3 The following DBI attributes are handled by DBD::File: =head4 AutoCommit Always on. =head4 ChopBlanks Works. =head4 NUM_OF_FIELDS Valid after C<< $sth->execute >>. =head4 NUM_OF_PARAMS Valid after C<< $sth->prepare >>. =head4 NAME Valid after C<< $sth->execute >>; undef for Non-Select statements. =head4 NULLABLE Not really working, always returns an array ref of ones, except the affected table has been created in this session. Valid after C<< $sth->execute >>; undef for non-select statements. =head3 Unsupported DBI attributes and methods =head4 bind_param_inout =head4 CursorName =head4 LongReadLen =head4 LongTruncOk =head3 DBD::File specific attributes In addition to the DBI attributes, you can use the following dbh attributes: =head4 f_dir This attribute is used for setting the directory where the files are opened and it defaults to the current directory (F<.>). Usually you set it on the dbh but it may be overridden per table (see L). When the value for C is a relative path, it is converted into the appropriate absolute path name (based on the current working directory) when the dbh attribute is set. f_dir => "/data/foo/csv", See L. =head4 f_dir_search This optional attribute can be set to pass a list of folders to also find existing tables. It will B be used to create new files. f_dir_search => [ "/data/bar/csv", "/dump/blargh/data" ], =head4 f_ext This attribute is used for setting the file extension. The format is: extension{/flag} where the /flag is optional and the extension is case-insensitive. C allows you to specify an extension which: f_ext => ".csv/r", =over =item * makes DBD::File prefer F over F. =item * makes the table name the filename minus the extension. =back DBI:CSV:f_dir=data;f_ext=.csv In the above example and when C contains both F and F
, DBD::File will open F and the table will be named "table". If F does not exist but F
does that file is opened and the table is also called "table". If C is not specified and F exists it will be opened and the table will be called "table.csv" which is probably not what you want. NOTE: even though extensions are case-insensitive, table names are not. DBI:CSV:f_dir=data;f_ext=.csv/r The C flag means the file extension is required and any filename that does not match the extension is ignored. Usually you set it on the dbh but it may be overridden per table (see L). =head4 f_schema This will set the schema name and defaults to the owner of the directory in which the table file resides. You can set C to C. my $dbh = DBI->connect ("dbi:CSV:", "", "", { f_schema => undef, f_dir => "data", f_ext => ".csv/r", }) or die $DBI::errstr; By setting the schema you affect the results from the tables call: my @tables = $dbh->tables (); # no f_schema "merijn".foo "merijn".bar # f_schema => "dbi" "dbi".foo "dbi".bar # f_schema => undef foo bar Defining C to the empty string is equal to setting it to C so the DSN can be C<"dbi:CSV:f_schema=;f_dir=.">. =head4 f_lock The C attribute is used to set the locking mode on the opened table files. Note that not all platforms support locking. By default, tables are opened with a shared lock for reading, and with an exclusive lock for writing. The supported modes are: 0: No locking at all. 1: Shared locks will be used. 2: Exclusive locks will be used. But see L below. =head4 f_lockfile If you wish to use a lockfile extension other than C<.lck>, simply specify the C attribute: $dbh = DBI->connect ("dbi:DBM:f_lockfile=.foo"); $dbh->{f_lockfile} = ".foo"; $dbh->{dbm_tables}{qux}{f_lockfile} = ".foo"; If you wish to disable locking, set the C to C<0>. $dbh = DBI->connect ("dbi:DBM:f_lockfile=0"); $dbh->{f_lockfile} = 0; $dbh->{dbm_tables}{qux}{f_lockfile} = 0; =head4 f_encoding With this attribute, you can set the encoding in which the file is opened. This is implemented using C<< binmode $fh, ":encoding()" >>. =head4 f_meta Private data area aliasing L which contains information about the tables this module handles. Table meta data might not be available until the table has been accessed for the first time e.g., by issuing a select on it however it is possible to pre-initialize attributes for each table you use. DBD::File recognizes the (public) attributes C, C, C, C, C, C, C, in addition to the attributes L already supports. Be very careful when modifying attributes you do not know, the consequence might be a destroyed or corrupted table. C is an attribute applicable to table meta data only and you will not find a corresponding attribute in the dbh. Whilst it may be reasonable to have several tables with the same column names, it is not for the same file name. If you need access to the same file using different table names, use C as the SQL engine and the C keyword: SELECT * FROM tbl AS t1, tbl AS t2 WHERE t1.id = t2.id C can be an absolute path name or a relative path name but if it is relative, it is interpreted as being relative to the C attribute of the table meta data. When C is set DBD::File will use C as specified and will not attempt to work out an alternative for C using the C
and C attribute. While C is a private and readonly attribute (which means, you cannot modify it's values), derived drivers might provide restricted write access through another attribute. Well known accessors are C for L, C for L and C for L. =head3 New opportunities for attributes from DBI::DBD::SqlEngine =head4 sql_table_source C<< $dbh->{sql_table_source} >> can be set to I (and is the default setting of DBD::File). This provides usual behaviour of previous DBD::File releases on @ary = DBI->data_sources ($driver); @ary = DBI->data_sources ($driver, \%attr); @ary = $dbh->data_sources (); @ary = $dbh->data_sources (\%attr); @names = $dbh->tables ($catalog, $schema, $table, $type); $sth = $dbh->table_info ($catalog, $schema, $table, $type); $sth = $dbh->table_info ($catalog, $schema, $table, $type, \%attr); $dbh->func ("list_tables"); =head4 sql_data_source C<< $dbh->{sql_data_source} >> can be set to either I, which is default and provides the well known behavior of DBD::File releases prior to 0.41, or I, which reuses already opened file-handle for operations. =head3 Internally private attributes to deal with SQL backends Do not modify any of these private attributes unless you understand the implications of doing so. The behavior of DBD::File and derived DBDs might be unpredictable when one or more of those attributes are modified. =head4 sql_nano_version Contains the version of loaded DBI::SQL::Nano. =head4 sql_statement_version Contains the version of loaded SQL::Statement. =head4 sql_handler Contains either the text 'SQL::Statement' or 'DBI::SQL::Nano'. =head4 sql_ram_tables Contains optionally temporary tables. =head4 sql_flags Contains optional flags to instantiate the SQL::Parser parsing engine when SQL::Statement is used as SQL engine. See L for valid flags. =head2 Driver private methods =head3 Default DBI methods =head4 data_sources The C method returns a list of subdirectories of the current directory in the form "dbi:CSV:f_dir=$dirname". If you want to read the subdirectories of another directory, use my ($drh) = DBI->install_driver ("CSV"); my (@list) = $drh->data_sources (f_dir => "/usr/local/csv_data"); =head3 Additional methods The following methods are only available via their documented name when DBD::File is used directly. Because this is only reasonable for testing purposes, the real names must be used instead. Those names can be computed by replacing the C in the method name with the driver prefix. =head4 f_versions Signature: sub f_versions (;$) { my ($table_name) = @_; $table_name ||= "."; ... } Returns the versions of the driver, including the DBI version, the Perl version, DBI::PurePerl version (if DBI::PurePerl is active) and the version of the SQL engine in use. my $dbh = DBI->connect ("dbi:File:"); my $f_versions = $dbh->func ("f_versions"); print "$f_versions\n"; __END__ # DBD::File 0.41 using IO::File (1.16) # DBI::DBD::SqlEngine 0.05 using SQL::Statement 1.406 # DBI 1.623 # OS darwin (12.2.1) # Perl 5.017006 (darwin-thread-multi-ld-2level) Called in list context, f_versions will return an array containing each line as single entry. Some drivers might use the optional (table name) argument and modify version information related to the table (e.g. DBD::DBM provides storage backend information for the requested table, when it has a table name). =head1 KNOWN BUGS AND LIMITATIONS =over 4 =item * This module uses flock () internally but flock is not available on all platforms. On MacOS and Windows 95 there is no locking at all (perhaps not so important on MacOS and Windows 95, as there is only a single user). =item * The module stores details about the handled tables in a private area of the driver handle (C<$drh>). This data area is not shared between different driver instances, so several C<< DBI->connect () >> calls will cause different table instances and private data areas. This data area is filled for the first time when a table is accessed, either via an SQL statement or via C and is not destroyed until the table is dropped or the driver handle is released. Manual destruction is possible via L. The following attributes are preserved in the data area and will evaluated instead of driver globals: =over 8 =item f_ext =item f_dir =item f_dir_search =item f_lock =item f_lockfile =item f_encoding =item f_schema =item col_names =item sql_identifier_case =back The following attributes are preserved in the data area only and cannot be set globally. =over 8 =item f_file =back The following attributes are preserved in the data area only and are computed when initializing the data area: =over 8 =item f_fqfn =item f_fqbn =item f_fqln =item table_name =back For DBD::CSV tables this means, once opened "foo.csv" as table named "foo", another table named "foo" accessing the file "foo.txt" cannot be opened. Accessing "foo" will always access the file "foo.csv" in memorized C, locking C via memorized C. You can use L or the C attribute for a specific table to work around this. =item * When used with SQL::Statement and temporary tables e.g., CREATE TEMP TABLE ... the table data processing bypasses DBD::File::Table. No file system calls will be made and there are no clashes with existing (file based) tables with the same name. Temporary tables are chosen over file tables, but they will not covered by C. =back =head1 AUTHOR This module is currently maintained by H.Merijn Brand < h.m.brand at xs4all.nl > and Jens Rehsack < rehsack at googlemail.com > The original author is Jochen Wiedmann. =head1 COPYRIGHT AND LICENSE Copyright (C) 2009-2013 by H.Merijn Brand & Jens Rehsack Copyright (C) 2004-2009 by Jeff Zucker Copyright (C) 1998-2004 by Jochen Wiedmann All rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =head1 SEE ALSO L, L, L, L, L, L, and L =cut PK1]! Sponge.pmnu[use strict; { package DBD::Sponge; require DBI; require Carp; our @EXPORT = qw(); # Do NOT @EXPORT anything. our $VERSION = "12.010003"; # $Id: Sponge.pm 10002 2007-09-26 21:03:25Z Tim $ # # Copyright (c) 1994-2003 Tim Bunce Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. our $drh = undef; # holds driver handle once initialised my $methods_already_installed; sub driver{ return $drh if $drh; DBD::Sponge::db->install_method("sponge_test_installed_method") unless $methods_already_installed++; my($class, $attr) = @_; $class .= "::dr"; ($drh) = DBI::_new_drh($class, { 'Name' => 'Sponge', 'Version' => $VERSION, 'Attribution' => "DBD::Sponge $VERSION (fake cursor driver) by Tim Bunce", }); $drh; } sub CLONE { undef $drh; } } { package DBD::Sponge::dr; # ====== DRIVER ====== our $imp_data_size = 0; # we use default (dummy) connect method } { package DBD::Sponge::db; # ====== DATABASE ====== our $imp_data_size = 0; use strict; sub prepare { my($dbh, $statement, $attribs) = @_; my $rows = delete $attribs->{'rows'} or return $dbh->set_err($DBI::stderr,"No rows attribute supplied to prepare"); my ($outer, $sth) = DBI::_new_sth($dbh, { 'Statement' => $statement, 'rows' => $rows, (map { exists $attribs->{$_} ? ($_=>$attribs->{$_}) : () } qw(execute_hook) ), }); if (my $behave_like = $attribs->{behave_like}) { $outer->{$_} = $behave_like->{$_} foreach (qw(RaiseError PrintError HandleError ShowErrorStatement)); } if ($statement =~ /^\s*insert\b/) { # very basic, just for testing execute_array() $sth->{is_insert} = 1; my $NUM_OF_PARAMS = $attribs->{NUM_OF_PARAMS} or return $dbh->set_err($DBI::stderr,"NUM_OF_PARAMS not specified for INSERT statement"); $sth->STORE('NUM_OF_PARAMS' => $attribs->{NUM_OF_PARAMS} ); } else { #assume select # we need to set NUM_OF_FIELDS my $numFields; if ($attribs->{'NUM_OF_FIELDS'}) { $numFields = $attribs->{'NUM_OF_FIELDS'}; } elsif ($attribs->{'NAME'}) { $numFields = @{$attribs->{NAME}}; } elsif ($attribs->{'TYPE'}) { $numFields = @{$attribs->{TYPE}}; } elsif (my $firstrow = $rows->[0]) { $numFields = scalar @$firstrow; } else { return $dbh->set_err($DBI::stderr, 'Cannot determine NUM_OF_FIELDS'); } $sth->STORE('NUM_OF_FIELDS' => $numFields); $sth->{NAME} = $attribs->{NAME} || [ map { "col$_" } 1..$numFields ]; $sth->{TYPE} = $attribs->{TYPE} || [ (DBI::SQL_VARCHAR()) x $numFields ]; $sth->{PRECISION} = $attribs->{PRECISION} || [ map { length($sth->{NAME}->[$_]) } 0..$numFields -1 ]; $sth->{SCALE} = $attribs->{SCALE} || [ (0) x $numFields ]; $sth->{NULLABLE} = $attribs->{NULLABLE} || [ (2) x $numFields ]; } $outer; } sub type_info_all { my ($dbh) = @_; my $ti = [ { TYPE_NAME => 0, DATA_TYPE => 1, PRECISION => 2, LITERAL_PREFIX => 3, LITERAL_SUFFIX => 4, CREATE_PARAMS => 5, NULLABLE => 6, CASE_SENSITIVE => 7, SEARCHABLE => 8, UNSIGNED_ATTRIBUTE=> 9, MONEY => 10, AUTO_INCREMENT => 11, LOCAL_TYPE_NAME => 12, MINIMUM_SCALE => 13, MAXIMUM_SCALE => 14, }, [ 'VARCHAR', DBI::SQL_VARCHAR(), undef, "'","'", undef, 0, 1, 1, 0, 0,0,undef,0,0 ], ]; return $ti; } sub FETCH { my ($dbh, $attrib) = @_; # In reality this would interrogate the database engine to # either return dynamic values that cannot be precomputed # or fetch and cache attribute values too expensive to prefetch. return 1 if $attrib eq 'AutoCommit'; # else pass up to DBI to handle return $dbh->SUPER::FETCH($attrib); } sub STORE { my ($dbh, $attrib, $value) = @_; # would normally validate and only store known attributes # else pass up to DBI to handle if ($attrib eq 'AutoCommit') { return 1 if $value; # is already set Carp::croak("Can't disable AutoCommit"); } return $dbh->SUPER::STORE($attrib, $value); } sub sponge_test_installed_method { my ($dbh, @args) = @_; return $dbh->set_err(42, "not enough parameters") unless @args >= 2; return \@args; } } { package DBD::Sponge::st; # ====== STATEMENT ====== our $imp_data_size = 0; use strict; sub execute { my $sth = shift; # hack to support ParamValues (when not using bind_param) $sth->{ParamValues} = (@_) ? { map { $_ => $_[$_-1] } 1..@_ } : undef; if (my $hook = $sth->{execute_hook}) { &$hook($sth, @_) or return; } if ($sth->{is_insert}) { my $row; $row = (@_) ? [ @_ ] : die "bind_param not supported yet" ; my $NUM_OF_PARAMS = $sth->{NUM_OF_PARAMS}; return $sth->set_err($DBI::stderr, @$row." values bound (@$row) but $NUM_OF_PARAMS expected") if @$row != $NUM_OF_PARAMS; { local $^W; $sth->trace_msg("inserting (@$row)\n"); } push @{ $sth->{rows} }, $row; } else { # mark select sth as Active $sth->STORE(Active => 1); } # else do nothing for select as data is already in $sth->{rows} return 1; } sub fetch { my ($sth) = @_; my $row = shift @{$sth->{'rows'}}; unless ($row) { $sth->STORE(Active => 0); return undef; } return $sth->_set_fbav($row); } *fetchrow_arrayref = \&fetch; sub FETCH { my ($sth, $attrib) = @_; # would normally validate and only fetch known attributes # else pass up to DBI to handle return $sth->SUPER::FETCH($attrib); } sub STORE { my ($sth, $attrib, $value) = @_; # would normally validate and only store known attributes # else pass up to DBI to handle return $sth->SUPER::STORE($attrib, $value); } } 1; __END__ =pod =head1 NAME DBD::Sponge - Create a DBI statement handle from Perl data =head1 SYNOPSIS my $sponge = DBI->connect("dbi:Sponge:","","",{ RaiseError => 1 }); my $sth = $sponge->prepare($statement, { rows => $data, NAME => $names, %attr } ); =head1 DESCRIPTION DBD::Sponge is useful for making a Perl data structure accessible through a standard DBI statement handle. This may be useful to DBD module authors who need to transform data in this way. =head1 METHODS =head2 connect() my $sponge = DBI->connect("dbi:Sponge:","","",{ RaiseError => 1 }); Here's a sample syntax for creating a database handle for the Sponge driver. No username and password are needed. =head2 prepare() my $sth = $sponge->prepare($statement, { rows => $data, NAME => $names, %attr } ); =over 4 =item * The C<$statement> here is an arbitrary statement or name you want to provide as identity of your data. If you're using DBI::Profile it will appear in the profile data. Generally it's expected that you are preparing a statement handle as if a C
for gotchas and warnings about the use of flock(). =head1 BUGS AND LIMITATIONS This module uses hash interfaces of two column file databases. While none of supported SQL engines have support for indices, the following statements really do the same (even if they mean something completely different) for each dbm type which lacks C support: $sth->do( "insert into foo values (1, 'hello')" ); # this statement does ... $sth->do( "update foo set v='world' where k=1" ); # ... the same as this statement $sth->do( "insert into foo values (1, 'world')" ); This is considered to be a bug and might change in a future release. Known affected dbm types are C and C. We highly recommended you use a more modern dbm type such as C. =head1 GETTING HELP, MAKING SUGGESTIONS, AND REPORTING BUGS If you need help installing or using DBD::DBM, please write to the DBI users mailing list at dbi-users@perl.org or to the comp.lang.perl.modules newsgroup on usenet. I cannot always answer every question quickly but there are many on the mailing list or in the newsgroup who can. DBD developers for DBD's which rely on DBD::File or DBD::DBM or use one of them as an example are suggested to join the DBI developers mailing list at dbi-dev@perl.org and strongly encouraged to join our IRC channel at L. If you have suggestions, ideas for improvements, or bugs to report, please report a bug as described in DBI. Do not mail any of the authors directly, you might not get an answer. When reporting bugs, please send the output of $dbh->dbm_versions($table) for a table that exhibits the bug and as small a sample as you can make of the code that produces the bug. And of course, patches are welcome, too :-). If you need enhancements quickly, you can get commercial support as described at L or you can contact Jens Rehsack at rehsack@cpan.org for commercial support in Germany. Please don't bother Jochen Wiedmann or Jeff Zucker for support - they handed over further maintenance to H.Merijn Brand and Jens Rehsack. =head1 ACKNOWLEDGEMENTS Many, many thanks to Tim Bunce for prodding me to write this, and for copious, wise, and patient suggestions all along the way. (Jeff Zucker) I send my thanks and acknowledgements to H.Merijn Brand for his initial refactoring of DBD::File and his strong and ongoing support of SQL::Statement. Without him, the current progress would never have been made. And I have to name Martin J. Evans for each laugh (and correction) of all those funny word creations I (as non-native speaker) made to the documentation. And - of course - I have to thank all those unnamed contributors and testers from the Perl community. (Jens Rehsack) =head1 AUTHOR AND COPYRIGHT This module is written by Jeff Zucker < jzucker AT cpan.org >, who also maintained it till 2007. After that, in 2010, Jens Rehsack & H.Merijn Brand took over maintenance. Copyright (c) 2004 by Jeff Zucker, all rights reserved. Copyright (c) 2010-2013 by Jens Rehsack & H.Merijn Brand, all rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =head1 SEE ALSO L, L, L, L, L, L, L, L, L =cut PK1]}0Gofer.pmnu[{ package DBD::Gofer; use strict; require DBI; require DBI::Gofer::Request; require DBI::Gofer::Response; require Carp; our $VERSION = "0.015327"; # $Id: Gofer.pm 15326 2012-06-06 16:32:38Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. # attributes we'll allow local STORE our %xxh_local_store_attrib = map { $_=>1 } qw( Active CachedKids Callbacks DbTypeSubclass ErrCount Executed FetchHashKeyName HandleError HandleSetErr InactiveDestroy AutoInactiveDestroy PrintError PrintWarn Profile RaiseError RootClass ShowErrorStatement Taint TaintIn TaintOut TraceLevel Warn dbi_quote_identifier_cache dbi_connect_closure dbi_go_execute_unique ); our %xxh_local_store_attrib_if_same_value = map { $_=>1 } qw( Username dbi_connect_method ); our $drh = undef; # holds driver handle once initialized our $methods_already_installed; sub driver{ return $drh if $drh; DBI->setup_driver('DBD::Gofer'); unless ($methods_already_installed++) { my $opts = { O=> 0x0004 }; # IMA_KEEP_ERR DBD::Gofer::db->install_method('go_dbh_method', $opts); DBD::Gofer::st->install_method('go_sth_method', $opts); DBD::Gofer::st->install_method('go_clone_sth', $opts); DBD::Gofer::db->install_method('go_cache', $opts); DBD::Gofer::st->install_method('go_cache', $opts); } my($class, $attr) = @_; $class .= "::dr"; ($drh) = DBI::_new_drh($class, { 'Name' => 'Gofer', 'Version' => $VERSION, 'Attribution' => 'DBD Gofer by Tim Bunce', }); $drh; } sub CLONE { undef $drh; } sub go_cache { my $h = shift; $h->{go_cache} = shift if @_; # return handle's override go_cache, if it has one return $h->{go_cache} if defined $h->{go_cache}; # or else the transports default go_cache return $h->{go_transport}->{go_cache}; } sub set_err_from_response { # set error/warn/info and propagate warnings my $h = shift; my $response = shift; if (my $warnings = $response->warnings) { warn $_ for @$warnings; } my ($err, $errstr, $state) = $response->err_errstr_state; # Only set_err() if there's an error else leave the current values # (The current values will normally be set undef by the DBI dispatcher # except for methods marked KEEPERR such as ping.) $h->set_err($err, $errstr, $state) if defined $err; return undef; } sub install_methods_proxy { my ($installed_methods) = @_; while ( my ($full_method, $attr) = each %$installed_methods ) { # need to install both a DBI dispatch stub and a proxy stub # (the dispatch stub may be already here due to local driver use) DBI->_install_method($full_method, "", $attr||{}) unless defined &{$full_method}; # now install proxy stubs on the driver side $full_method =~ m/^DBI::(\w\w)::(\w+)$/ or die "Invalid method name '$full_method' for install_method"; my ($type, $method) = ($1, $2); my $driver_method = "DBD::Gofer::${type}::${method}"; next if defined &{$driver_method}; my $sub; if ($type eq 'db') { $sub = sub { return shift->go_dbh_method(undef, $method, @_) }; } else { $sub = sub { shift->set_err($DBI::stderr, "Can't call \$${type}h->$method when using DBD::Gofer"); return; }; } no strict 'refs'; *$driver_method = $sub; } } } { package DBD::Gofer::dr; # ====== DRIVER ====== $imp_data_size = 0; use strict; sub connect_cached { my ($drh, $dsn, $user, $auth, $attr)= @_; $attr ||= {}; return $drh->SUPER::connect_cached($dsn, $user, $auth, { (%$attr), go_connect_method => $attr->{go_connect_method} || 'connect_cached', }); } sub connect { my($drh, $dsn, $user, $auth, $attr)= @_; my $orig_dsn = $dsn; # first remove dsn= and everything after it my $remote_dsn = ($dsn =~ s/;?\bdsn=(.*)$// && $1) or return $drh->set_err($DBI::stderr, "No dsn= argument in '$orig_dsn'"); if ($attr->{go_bypass}) { # don't use DBD::Gofer for this connection # useful for testing with DBI_AUTOPROXY, e.g., t/03handle.t return DBI->connect($remote_dsn, $user, $auth, $attr); } my %go_attr; # extract any go_ attributes from the connect() attr arg for my $k (grep { /^go_/ } keys %$attr) { $go_attr{$k} = delete $attr->{$k}; } # then override those with any attributes embedded in our dsn (not remote_dsn) for my $kv (grep /=/, split /;/, $dsn, -1) { my ($k, $v) = split /=/, $kv, 2; $go_attr{ "go_$k" } = $v; } if (not ref $go_attr{go_policy}) { # if not a policy object already my $policy_class = $go_attr{go_policy} || 'classic'; $policy_class = "DBD::Gofer::Policy::$policy_class" unless $policy_class =~ /::/; _load_class($policy_class) or return $drh->set_err($DBI::stderr, "Can't load $policy_class: $@"); # replace policy name in %go_attr with policy object $go_attr{go_policy} = eval { $policy_class->new(\%go_attr) } or return $drh->set_err($DBI::stderr, "Can't instanciate $policy_class: $@"); } # policy object is left in $go_attr{go_policy} so transport can see it my $go_policy = $go_attr{go_policy}; if ($go_attr{go_cache} and not ref $go_attr{go_cache}) { # if not a cache object already my $cache_class = $go_attr{go_cache}; $cache_class = "DBI::Util::CacheMemory" if $cache_class eq '1'; _load_class($cache_class) or return $drh->set_err($DBI::stderr, "Can't load $cache_class $@"); $go_attr{go_cache} = eval { $cache_class->new() } or $drh->set_err(0, "Can't instanciate $cache_class: $@"); # warning } # delete any other attributes that don't apply to transport my $go_connect_method = delete $go_attr{go_connect_method}; my $transport_class = delete $go_attr{go_transport} or return $drh->set_err($DBI::stderr, "No transport= argument in '$orig_dsn'"); $transport_class = "DBD::Gofer::Transport::$transport_class" unless $transport_class =~ /::/; _load_class($transport_class) or return $drh->set_err($DBI::stderr, "Can't load $transport_class: $@"); my $go_transport = eval { $transport_class->new(\%go_attr) } or return $drh->set_err($DBI::stderr, "Can't instanciate $transport_class: $@"); my $request_class = "DBI::Gofer::Request"; my $go_request = eval { my $go_attr = { %$attr }; # XXX user/pass of fwd server vs db server ? also impact of autoproxy if ($user) { $go_attr->{Username} = $user; $go_attr->{Password} = $auth; } # delete any attributes we can't serialize (or don't want to) delete @{$go_attr}{qw(Profile HandleError HandleSetErr Callbacks)}; # delete any attributes that should only apply to the client-side delete @{$go_attr}{qw(RootClass DbTypeSubclass)}; $go_connect_method ||= $go_policy->connect_method($remote_dsn, $go_attr) || 'connect'; $request_class->new({ dbh_connect_call => [ $go_connect_method, $remote_dsn, $user, $auth, $go_attr ], }) } or return $drh->set_err($DBI::stderr, "Can't instanciate $request_class: $@"); my ($dbh, $dbh_inner) = DBI::_new_dbh($drh, { 'Name' => $dsn, 'USER' => $user, go_transport => $go_transport, go_request => $go_request, go_policy => $go_policy, }); # mark as inactive temporarily for STORE. Active not set until connected() called. $dbh->STORE(Active => 0); # should we ping to check the connection # and fetch dbh attributes my $skip_connect_check = $go_policy->skip_connect_check($attr, $dbh); if (not $skip_connect_check) { if (not $dbh->go_dbh_method(undef, 'ping')) { return undef if $dbh->err; # error already recorded, typically return $dbh->set_err($DBI::stderr, "ping failed"); } } return $dbh; } sub _load_class { # return true or false+$@ my $class = shift; (my $pm = $class) =~ s{::}{/}g; $pm .= ".pm"; return 1 if eval { require $pm }; delete $INC{$pm}; # shouldn't be needed (perl bug?) and assigning undef isn't enough undef; # error in $@ } } { package DBD::Gofer::db; # ====== DATABASE ====== $imp_data_size = 0; use strict; use Carp qw(carp croak); my %dbh_local_store_attrib = %DBD::Gofer::xxh_local_store_attrib; sub connected { shift->STORE(Active => 1); } sub go_dbh_method { my $dbh = shift; my $meta = shift; # @_ now contains ($method_name, @args) my $request = $dbh->{go_request}; $request->init_request([ wantarray, @_ ], $dbh); ++$dbh->{go_request_count}; my $go_policy = $dbh->{go_policy}; my $dbh_attribute_update = $go_policy->dbh_attribute_update(); $request->dbh_attributes( $go_policy->dbh_attribute_list() ) if $dbh_attribute_update eq 'every' or $dbh->{go_request_count}==1; $request->dbh_last_insert_id_args($meta->{go_last_insert_id_args}) if $meta->{go_last_insert_id_args}; my $transport = $dbh->{go_transport} or return $dbh->set_err($DBI::stderr, "Not connected (no transport)"); local $transport->{go_cache} = $dbh->{go_cache} if defined $dbh->{go_cache}; my ($response, $retransmit_sub) = $transport->transmit_request($request); $response ||= $transport->receive_response($request, $retransmit_sub); $dbh->{go_response} = $response or die "No response object returned by $transport"; die "response '$response' returned by $transport is not a response object" unless UNIVERSAL::isa($response,"DBI::Gofer::Response"); if (my $dbh_attributes = $response->dbh_attributes) { # XXX installed_methods piggybacks on dbh_attributes for now if (my $installed_methods = delete $dbh_attributes->{dbi_installed_methods}) { DBD::Gofer::install_methods_proxy($installed_methods) if $dbh->{go_request_count}==1; } # XXX we don't STORE here, we just stuff the value into the attribute cache $dbh->{$_} = $dbh_attributes->{$_} for keys %$dbh_attributes; } my $rv = $response->rv; if (my $resultset_list = $response->sth_resultsets) { # dbh method call returned one or more resultsets # (was probably a metadata method like table_info) # # setup an sth but don't execute/forward it my $sth = $dbh->prepare(undef, { go_skip_prepare_check => 1 }); # set the sth response to our dbh response (tied %$sth)->{go_response} = $response; # setup the sth with the results in our response $sth->more_results; # and return that new sth as if it came from original request $rv = [ $sth ]; } elsif (!$rv) { # should only occur for major transport-level error #carp("no rv in response { @{[ %$response ]} }"); $rv = [ ]; } DBD::Gofer::set_err_from_response($dbh, $response); return (wantarray) ? @$rv : $rv->[0]; } # Methods that should be forwarded but can be cached for my $method (qw( tables table_info column_info primary_key_info foreign_key_info statistics_info data_sources type_info_all get_info parse_trace_flags parse_trace_flag func )) { my $policy_name = "cache_$method"; my $super_name = "SUPER::$method"; my $sub = sub { my $dbh = shift; my $rv; # if we know the remote side doesn't override the DBI's default method # then we might as well just call the DBI's default method on the client # (which may, in turn, call other methods that are forwarded, like get_info) if ($dbh->{dbi_default_methods}{$method} && $dbh->{go_policy}->skip_default_methods()) { $dbh->trace_msg(" !! $method: using local default as remote method is also default\n"); return $dbh->$super_name(@_); } my $cache; my $cache_key; if (my $cache_it = $dbh->{go_policy}->$policy_name(undef, $dbh, @_)) { $cache = $dbh->{go_meta_cache} ||= {}; # keep separate from go_cache $cache_key = sprintf "%s_wa%d(%s)", $policy_name, wantarray||0, join(",\t", map { # XXX basic but sufficient for now !ref($_) ? DBI::neat($_,1e6) : ref($_) eq 'ARRAY' ? DBI::neat_list($_,1e6,",\001") : ref($_) eq 'HASH' ? do { my @k = sort keys %$_; DBI::neat_list([@k,@{$_}{@k}],1e6,",\002") } : do { warn "unhandled argument type ($_)"; $_ } } @_); if ($rv = $cache->{$cache_key}) { $dbh->trace_msg("$method(@_) returning previously cached value ($cache_key)\n",4); my @cache_rv = @$rv; # if it's an sth we have to clone it $cache_rv[0] = $cache_rv[0]->go_clone_sth if UNIVERSAL::isa($cache_rv[0],'DBI::st'); return (wantarray) ? @cache_rv : $cache_rv[0]; } } $rv = [ (wantarray) ? ($dbh->go_dbh_method(undef, $method, @_)) : scalar $dbh->go_dbh_method(undef, $method, @_) ]; if ($cache) { $dbh->trace_msg("$method(@_) caching return value ($cache_key)\n",4); my @cache_rv = @$rv; # if it's an sth we have to clone it #$cache_rv[0] = $cache_rv[0]->go_clone_sth # if UNIVERSAL::isa($cache_rv[0],'DBI::st'); $cache->{$cache_key} = \@cache_rv unless UNIVERSAL::isa($cache_rv[0],'DBI::st'); # XXX cloning sth not yet done } return (wantarray) ? @$rv : $rv->[0]; }; no strict 'refs'; *$method = $sub; } # Methods that can use the DBI defaults for some situations/drivers for my $method (qw( quote quote_identifier )) { # XXX keep DBD::Gofer::Policy::Base in sync my $policy_name = "locally_$method"; my $super_name = "SUPER::$method"; my $sub = sub { my $dbh = shift; # if we know the remote side doesn't override the DBI's default method # then we might as well just call the DBI's default method on the client # (which may, in turn, call other methods that are forwarded, like get_info) if ($dbh->{dbi_default_methods}{$method} && $dbh->{go_policy}->skip_default_methods()) { $dbh->trace_msg(" !! $method: using local default as remote method is also default\n"); return $dbh->$super_name(@_); } # false: use remote gofer # 1: use local DBI default method # code ref: use the code ref my $locally = $dbh->{go_policy}->$policy_name($dbh, @_); if ($locally) { return $locally->($dbh, @_) if ref $locally eq 'CODE'; return $dbh->$super_name(@_); } return $dbh->go_dbh_method(undef, $method, @_); # propagate context }; no strict 'refs'; *$method = $sub; } # Methods that should always fail for my $method (qw( begin_work commit rollback )) { no strict 'refs'; *$method = sub { return shift->set_err($DBI::stderr, "$method not available with DBD::Gofer") } } sub do { my ($dbh, $sql, $attr, @args) = @_; delete $dbh->{Statement}; # avoid "Modification of non-creatable hash value attempted" $dbh->{Statement} = $sql; # for profiling and ShowErrorStatement my $meta = { go_last_insert_id_args => $attr->{go_last_insert_id_args} }; return $dbh->go_dbh_method($meta, 'do', $sql, $attr, @args); } sub ping { my $dbh = shift; return $dbh->set_err('', "can't ping while not connected") # info unless $dbh->SUPER::FETCH('Active'); my $skip_ping = $dbh->{go_policy}->skip_ping(); return ($skip_ping) ? 1 : $dbh->go_dbh_method(undef, 'ping', @_); } sub last_insert_id { my $dbh = shift; my $response = $dbh->{go_response} or return undef; return $response->last_insert_id; } sub FETCH { my ($dbh, $attrib) = @_; # FETCH is effectively already cached because the DBI checks the # attribute cache in the handle before calling FETCH # and this FETCH copies the value into the attribute cache # forward driver-private attributes (except ours) if ($attrib =~ m/^[a-z]/ && $attrib !~ /^go_/) { my $value = $dbh->go_dbh_method(undef, 'FETCH', $attrib); $dbh->{$attrib} = $value; # XXX forces caching by DBI return $dbh->{$attrib} = $value; } # else pass up to DBI to handle return $dbh->SUPER::FETCH($attrib); } sub STORE { my ($dbh, $attrib, $value) = @_; if ($attrib eq 'AutoCommit') { croak "Can't enable transactions when using DBD::Gofer" if !$value; return $dbh->SUPER::STORE($attrib => ($value) ? -901 : -900); } return $dbh->SUPER::STORE($attrib => $value) # we handle this attribute locally if $dbh_local_store_attrib{$attrib} # or it's a private_ (application) attribute or $attrib =~ /^private_/ # or not yet connected (ie being called by DBI->connect) or not $dbh->FETCH('Active'); return $dbh->SUPER::STORE($attrib => $value) if $DBD::Gofer::xxh_local_store_attrib_if_same_value{$attrib} && do { # values are the same my $crnt = $dbh->FETCH($attrib); local $^W; (defined($value) ^ defined($crnt)) ? 0 # definedness differs : $value eq $crnt; }; # dbh attributes are set at connect-time - see connect() carp("Can't alter \$dbh->{$attrib} after handle created with DBD::Gofer") if $dbh->FETCH('Warn'); return $dbh->set_err($DBI::stderr, "Can't alter \$dbh->{$attrib} after handle created with DBD::Gofer"); } sub disconnect { my $dbh = shift; $dbh->{go_transport} = undef; $dbh->STORE(Active => 0); } sub prepare { my ($dbh, $statement, $attr)= @_; return $dbh->set_err($DBI::stderr, "Can't prepare when disconnected") unless $dbh->FETCH('Active'); $attr = { %$attr } if $attr; # copy so we can edit my $policy = delete($attr->{go_policy}) || $dbh->{go_policy}; my $lii_args = delete $attr->{go_last_insert_id_args}; my $go_prepare = delete($attr->{go_prepare_method}) || $dbh->{go_prepare_method} || $policy->prepare_method($dbh, $statement, $attr) || 'prepare'; # e.g. for code not using placeholders my $go_cache = delete $attr->{go_cache}; # set to undef if there are no attributes left for the actual prepare call $attr = undef if $attr and not %$attr; my ($sth, $sth_inner) = DBI::_new_sth($dbh, { Statement => $statement, go_prepare_call => [ 0, $go_prepare, $statement, $attr ], # go_method_calls => [], # autovivs if needed go_request => $dbh->{go_request}, go_transport => $dbh->{go_transport}, go_policy => $policy, go_last_insert_id_args => $lii_args, go_cache => $go_cache, }); $sth->STORE(Active => 0); # XXX needed? It should be the default my $skip_prepare_check = $policy->skip_prepare_check($attr, $dbh, $statement, $attr, $sth); if (not $skip_prepare_check) { $sth->go_sth_method() or return undef; } return $sth; } sub prepare_cached { my ($dbh, $sql, $attr, $if_active)= @_; $attr ||= {}; return $dbh->SUPER::prepare_cached($sql, { %$attr, go_prepare_method => $attr->{go_prepare_method} || 'prepare_cached', }, $if_active); } *go_cache = \&DBD::Gofer::go_cache; } { package DBD::Gofer::st; # ====== STATEMENT ====== $imp_data_size = 0; use strict; my %sth_local_store_attrib = (%DBD::Gofer::xxh_local_store_attrib, NUM_OF_FIELDS => 1); sub go_sth_method { my ($sth, $meta) = @_; if (my $ParamValues = $sth->{ParamValues}) { my $ParamAttr = $sth->{ParamAttr}; # XXX the sort here is a hack to work around a DBD::Sybase bug # but only works properly for params 1..9 # (reverse because of the unshift) my @params = reverse sort keys %$ParamValues; if (@params > 9 && ($sth->{Database}{go_dsn}||'') =~ /dbi:Sybase/) { # if more than 9 then we need to do a proper numeric sort # also warn to alert user of this issue warn "Sybase param binding order hack in use"; @params = sort { $b <=> $a } @params; } for my $p (@params) { # unshift to put binds before execute call unshift @{ $sth->{go_method_calls} }, [ 'bind_param', $p, $ParamValues->{$p}, $ParamAttr->{$p} ]; } } my $dbh = $sth->{Database} or die "panic"; ++$dbh->{go_request_count}; my $request = $sth->{go_request}; $request->init_request($sth->{go_prepare_call}, $sth); $request->sth_method_calls(delete $sth->{go_method_calls}) if $sth->{go_method_calls}; $request->sth_result_attr({}); # (currently) also indicates this is an sth request $request->dbh_last_insert_id_args($meta->{go_last_insert_id_args}) if $meta->{go_last_insert_id_args}; my $go_policy = $sth->{go_policy}; my $dbh_attribute_update = $go_policy->dbh_attribute_update(); $request->dbh_attributes( $go_policy->dbh_attribute_list() ) if $dbh_attribute_update eq 'every' or $dbh->{go_request_count}==1; my $transport = $sth->{go_transport} or return $sth->set_err($DBI::stderr, "Not connected (no transport)"); local $transport->{go_cache} = $sth->{go_cache} if defined $sth->{go_cache}; my ($response, $retransmit_sub) = $transport->transmit_request($request); $response ||= $transport->receive_response($request, $retransmit_sub); $sth->{go_response} = $response or die "No response object returned by $transport"; $dbh->{go_response} = $response; # mainly for last_insert_id if (my $dbh_attributes = $response->dbh_attributes) { # XXX we don't STORE here, we just stuff the value into the attribute cache $dbh->{$_} = $dbh_attributes->{$_} for keys %$dbh_attributes; # record the values returned, so we know that we have fetched # values are which we have fetched (see dbh->FETCH method) $dbh->{go_dbh_attributes_fetched} = $dbh_attributes; } my $rv = $response->rv; # may be undef on error if ($response->sth_resultsets) { # setup first resultset - including sth attributes $sth->more_results; } else { $sth->STORE(Active => 0); $sth->{go_rows} = $rv; } # set error/warn/info (after more_results as that'll clear err) DBD::Gofer::set_err_from_response($sth, $response); return $rv; } sub bind_param { my ($sth, $param, $value, $attr) = @_; $sth->{ParamValues}{$param} = $value; $sth->{ParamAttr}{$param} = $attr if defined $attr; # attr is sticky if not explicitly set return 1; } sub execute { my $sth = shift; $sth->bind_param($_, $_[$_-1]) for (1..@_); push @{ $sth->{go_method_calls} }, [ 'execute' ]; my $meta = { go_last_insert_id_args => $sth->{go_last_insert_id_args} }; return $sth->go_sth_method($meta); } sub more_results { my $sth = shift; $sth->finish; my $response = $sth->{go_response} or do { # e.g., we haven't sent a request yet (ie prepare then more_results) $sth->trace_msg(" No response object present", 3); return; }; my $resultset_list = $response->sth_resultsets or return $sth->set_err($DBI::stderr, "No sth_resultsets"); my $meta = shift @$resultset_list or return undef; # no more result sets #warn "more_results: ".Data::Dumper::Dumper($meta); # pull out the special non-attributes first my ($rowset, $err, $errstr, $state) = delete @{$meta}{qw(rowset err errstr state)}; # copy meta attributes into attribute cache my $NUM_OF_FIELDS = delete $meta->{NUM_OF_FIELDS}; $sth->STORE('NUM_OF_FIELDS', $NUM_OF_FIELDS); # XXX need to use STORE for some? $sth->{$_} = $meta->{$_} for keys %$meta; if (($NUM_OF_FIELDS||0) > 0) { $sth->{go_rows} = ($rowset) ? @$rowset : -1; $sth->{go_current_rowset} = $rowset; $sth->{go_current_rowset_err} = [ $err, $errstr, $state ] if defined $err; $sth->STORE(Active => 1) if $rowset; } return $sth; } sub go_clone_sth { my ($sth1) = @_; # clone an (un-fetched-from) sth - effectively undoes the initial more_results # not 100% so just for use in caching returned sth e.g. table_info my $sth2 = $sth1->{Database}->prepare($sth1->{Statement}, { go_skip_prepare_check => 1 }); $sth2->STORE($_, $sth1->{$_}) for qw(NUM_OF_FIELDS Active); my $sth2_inner = tied %$sth2; $sth2_inner->{$_} = $sth1->{$_} for qw(NUM_OF_PARAMS FetchHashKeyName); die "not fully implemented yet"; return $sth2; } sub fetchrow_arrayref { my ($sth) = @_; my $resultset = $sth->{go_current_rowset} || do { # should only happen if fetch called after execute failed my $rowset_err = $sth->{go_current_rowset_err} || [ 1, 'no result set (did execute fail)' ]; return $sth->set_err( @$rowset_err ); }; return $sth->_set_fbav(shift @$resultset) if @$resultset; $sth->finish; # no more data so finish return undef; } *fetch = \&fetchrow_arrayref; # alias sub fetchall_arrayref { my ($sth, $slice, $max_rows) = @_; my $resultset = $sth->{go_current_rowset} || do { # should only happen if fetch called after execute failed my $rowset_err = $sth->{go_current_rowset_err} || [ 1, 'no result set (did execute fail)' ]; return $sth->set_err( @$rowset_err ); }; my $mode = ref($slice) || 'ARRAY'; return $sth->SUPER::fetchall_arrayref($slice, $max_rows) if ref($slice) or defined $max_rows; $sth->finish; # no more data after this so finish return $resultset; } sub rows { return shift->{go_rows}; } sub STORE { my ($sth, $attrib, $value) = @_; return $sth->SUPER::STORE($attrib => $value) if $sth_local_store_attrib{$attrib} # handle locally # or it's a private_ (application) attribute or $attrib =~ /^private_/; # otherwise warn but do it anyway # this will probably need refining later my $msg = "Altering \$sth->{$attrib} won't affect proxied handle"; Carp::carp($msg) if $sth->FETCH('Warn'); # XXX could perhaps do # push @{ $sth->{go_method_calls} }, [ 'STORE', $attrib, $value ] # if not $sth->FETCH('Executed'); # but how to handle repeat executions? How to we know when an # attribute is being set to affect the current resultset or the # next execution? # Could just always use go_method_calls I guess. # do the store locally anyway, just in case $sth->SUPER::STORE($attrib => $value); return $sth->set_err($DBI::stderr, $msg); } # sub bind_param_array # we use DBI's default, which sets $sth->{ParamArrays}{$param} = $value # and calls bind_param($param, undef, $attr) if $attr. sub execute_array { my $sth = shift; my $attr = shift; $sth->bind_param_array($_, $_[$_-1]) for (1..@_); push @{ $sth->{go_method_calls} }, [ 'execute_array', $attr ]; return $sth->go_sth_method($attr); } *go_cache = \&DBD::Gofer::go_cache; } 1; __END__ =head1 NAME DBD::Gofer - A stateless-proxy driver for communicating with a remote DBI =head1 SYNOPSIS use DBI; $original_dsn = "dbi:..."; # your original DBI Data Source Name $dbh = DBI->connect("dbi:Gofer:transport=$transport;...;dsn=$original_dsn", $user, $passwd, \%attributes); ... use $dbh as if it was connected to $original_dsn ... The C part specifies the name of the module to use to transport the requests to the remote DBI. If $transport doesn't contain any double colons then it's prefixed with C. The C part I of the DSN because everything after C is assumed to be the DSN that the remote DBI should use. The C<...> represents attributes that influence the operation of the Gofer driver or transport. These are described below or in the documentation of the transport module being used. =encoding ISO8859-1 =head1 DESCRIPTION DBD::Gofer is a DBI database driver that forwards requests to another DBI driver, usually in a separate process, often on a separate machine. It tries to be as transparent as possible so it appears that you are using the remote driver directly. DBD::Gofer is very similar to DBD::Proxy. The major difference is that with DBD::Gofer no state is maintained on the remote end. That means every request contains all the information needed to create the required state. (So, for example, every request includes the DSN to connect to.) Each request can be sent to any available server. The server executes the request and returns a single response that includes all the data. This is very similar to the way http works as a stateless protocol for the web. Each request from your web browser can be handled by a different web server process. =head2 Use Cases This may seem like pointless overhead but there are situations where this is a very good thing. Let's consider a specific case. Imagine using DBD::Gofer with an http transport. Your application calls connect(), prepare("select * from table where foo=?"), bind_param(), and execute(). At this point DBD::Gofer builds a request containing all the information about the method calls. It then uses the httpd transport to send that request to an apache web server. This 'dbi execute' web server executes the request (using DBI::Gofer::Execute and related modules) and builds a response that contains all the rows of data, if the statement returned any, along with all the attributes that describe the results, such as $sth->{NAME}. This response is sent back to DBD::Gofer which unpacks it and presents it to the application as if it had executed the statement itself. =head2 Advantages Okay, but you still don't see the point? Well let's consider what we've gained: =head3 Connection Pooling and Throttling The 'dbi execute' web server leverages all the functionality of web infrastructure in terms of load balancing, high-availability, firewalls, access management, proxying, caching. At its most basic level you get a configurable pool of persistent database connections. =head3 Simple Scaling Got thousands of processes all trying to connect to the database? You can use DBD::Gofer to connect them to your smaller pool of 'dbi execute' web servers instead. =head3 Caching Client-side caching is as simple as adding "C" to the DSN. This feature alone can be worth using DBD::Gofer for. =head3 Fewer Network Round-trips DBD::Gofer sends as few requests as possible (dependent on the policy being used). =head3 Thin Clients / Unsupported Platforms You no longer need drivers for your database on every system. DBD::Gofer is pure perl. =head1 CONSTRAINTS There are some natural constraints imposed by the DBD::Gofer 'stateless' approach. But not many: =head2 You can't change database handle attributes after connect() You can't change database handle attributes after you've connected. Use the connect() call to specify all the attribute settings you want. This is because it's critical that when a request is complete the database handle is left in the same state it was when first connected. An exception is made for attributes with names starting "C": They can be set after connect() but the change is only applied locally. =head2 You can't change statement handle attributes after prepare() You can't change statement handle attributes after prepare. An exception is made for attributes with names starting "C": They can be set after prepare() but the change is only applied locally. =head2 You can't use transactions AutoCommit only. Transactions aren't supported. (In theory transactions could be supported when using a transport that maintains a connection, like C does. If you're interested in this please get in touch via dbi-dev@perl.org) =head2 You can't call driver-private sth methods But that's rarely needed anyway. =head1 GENERAL CAVEATS A few important things to keep in mind when using DBD::Gofer: =head2 Temporary tables, locks, and other per-connection persistent state You shouldn't expect any per-session state to persist between requests. This includes locks and temporary tables. Because the server-side may execute your requests via a different database connections, you can't rely on any per-connection persistent state, such as temporary tables, being available from one request to the next. This is an easy trap to fall into. A good way to check for this is to test your code with a Gofer policy package that sets the C policy to 'connect' to force a new connection for each request. The C policy does this. =head2 Driver-private Database Handle Attributes Some driver-private dbh attributes may not be available if the driver has not implemented the private_attribute_info() method (added in DBI 1.54). =head2 Driver-private Statement Handle Attributes Driver-private sth attributes can be set in the prepare() call. TODO Some driver-private sth attributes may not be available if the driver has not implemented the private_attribute_info() method (added in DBI 1.54). =head2 Multiple Resultsets Multiple resultsets are supported only if the driver supports the more_results() method (an exception is made for DBD::Sybase). =head2 Statement activity that also updates dbh attributes Some drivers may update one or more dbh attributes after performing activity on a child sth. For example, DBD::mysql provides $dbh->{mysql_insertid} in addition to $sth->{mysql_insertid}. Currently mysql_insertid is supported via a hack but a more general mechanism is needed for other drivers to use. =head2 Methods that report an error always return undef With DBD::Gofer, a method that sets an error always return an undef or empty list. That shouldn't be a problem in practice because the DBI doesn't define any methods that return meaningful values while also reporting an error. =head2 Subclassing only applies to client-side The RootClass and DbTypeSubclass attributes are not passed to the Gofer server. =head1 CAVEATS FOR SPECIFIC METHODS =head2 last_insert_id To enable use of last_insert_id you need to indicate to DBD::Gofer that you'd like to use it. You do that my adding a C attribute to the do() or prepare() method calls. For example: $dbh->do($sql, { go_last_insert_id_args => [...] }); or $sth = $dbh->prepare($sql, { go_last_insert_id_args => [...] }); The array reference should contains the args that you want passed to the last_insert_id() method. =head2 execute_for_fetch The array methods bind_param_array() and execute_array() are supported. When execute_array() is called the data is serialized and executed in a single round-trip to the Gofer server. This makes it very fast, but requires enough memory to store all the serialized data. The execute_for_fetch() method currently isn't optimised, it uses the DBI fallback behaviour of executing each tuple individually. (It could be implemented as a wrapper for execute_array() - patches welcome.) =head1 TRANSPORTS DBD::Gofer doesn't concern itself with transporting requests and responses to and fro. For that it uses special Gofer transport modules. Gofer transport modules usually come in pairs: one for the 'client' DBD::Gofer driver to use and one for the remote 'server' end. They have very similar names: DBD::Gofer::Transport:: DBI::Gofer::Transport:: Sometimes the transports on the DBD and DBI sides may have different names. For example DBD::Gofer::Transport::http is typically used with DBI::Gofer::Transport::mod_perl (DBD::Gofer::Transport::http and DBI::Gofer::Transport::mod_perl modules are part of the GoferTransport-http distribution). =head2 Bundled Transports Several transport modules are provided with DBD::Gofer: =head3 null The null transport is the simplest of them all. It doesn't actually transport the request anywhere. It just serializes (freezes) the request into a string, then thaws it back into a data structure before passing it to DBI::Gofer::Execute to execute. The same freeze and thaw is applied to the results. The null transport is the best way to test if your application will work with Gofer. Just set the DBI_AUTOPROXY environment variable to "C" (see L below) and run your application, or ideally its test suite, as usual. It doesn't take any parameters. =head3 pipeone The pipeone transport launches a subprocess for each request. It passes in the request and reads the response. The fact that a new subprocess is started for each request ensures that the server side is truly stateless. While this does make the transport I slow, it is useful as a way to test that your application doesn't depend on per-connection state, such as temporary tables, persisting between requests. It's also useful both as a proof of concept and as a base class for the stream driver. =head3 stream The stream driver also launches a subprocess and writes requests and reads responses, like the pipeone transport. In this case, however, the subprocess is expected to handle more that one request. (Though it will be automatically restarted if it exits.) This is the first transport that is truly useful because it can launch the subprocess on a remote machine using C. This means you can now use DBD::Gofer to easily access any databases that's accessible from any system you can login to. You also get all the benefits of ssh, including encryption and optional compression. See L below for an example. =head2 Other Transports Implementing a Gofer transport is I simple, and more transports are very welcome. Just take a look at any existing transports that are similar to your needs. =head3 http See the GoferTransport-http distribution on CPAN: http://search.cpan.org/dist/GoferTransport-http/ =head3 Gearman I know Ask Bjørn Hansen has implemented a transport for the C distributed job system, though it's not on CPAN at the time of writing this. =head1 CONNECTING Simply prefix your existing DSN with "C" where $transport is the name of the Gofer transport you want to use (see L). The C and C attributes must be specified and the C attributes must be last. Other attributes can be specified in the DSN to configure DBD::Gofer and/or the Gofer transport module being used. The main attributes after C, are C and C. These and other attributes are described below. =head2 Using DBI_AUTOPROXY The simplest way to try out DBD::Gofer is to set the DBI_AUTOPROXY environment variable. In this case you don't include the C part. For example: export DBI_AUTOPROXY="dbi:Gofer:transport=null" or, for a more useful example, try: export DBI_AUTOPROXY="dbi:Gofer:transport=stream;url=ssh:user@example.com" =head2 Connection Attributes These attributes can be specified in the DSN. They can also be passed in the \%attr parameter of the DBI connect method by adding a "C" prefix to the name. =head3 transport Specifies the Gofer transport class to use. Required. See L above. If the value does not include C<::> then "C" is prefixed. The transport object can be accessed via $h->{go_transport}. =head3 dsn Specifies the DSN for the remote side to connect to. Required, and must be last. =head3 url Used to tell the transport where to connect to. The exact form of the value depends on the transport used. =head3 policy Specifies the policy to use. See L. If the value does not include C<::> then "C" is prefixed. The policy object can be accessed via $h->{go_policy}. =head3 timeout Specifies a timeout, in seconds, to use when waiting for responses from the server side. =head3 retry_limit Specifies the number of times a failed request will be retried. Default is 0. =head3 retry_hook Specifies a code reference to be called to decide if a failed request should be retried. The code reference is called like this: $transport = $h->{go_transport}; $retry = $transport->go_retry_hook->($request, $response, $transport); If it returns true then the request will be retried, up to the C. If it returns a false but defined value then the request will not be retried. If it returns undef then the default behaviour will be used, as if C had not been specified. The default behaviour is to retry requests where $request->is_idempotent is true, or the error message matches C. =head3 cache Specifies that client-side caching should be performed. The value is the name of a cache class to use. Any class implementing get($key) and set($key, $value) methods can be used. That includes a great many powerful caching classes on CPAN, including the Cache and Cache::Cache distributions. You can use "C" is a shortcut for "C". See L for a description of this simple fast default cache. The cache object can be accessed via $h->go_cache. For example: $dbh->go_cache->clear; # free up memory being used by the cache The cache keys are the frozen (serialized) requests, and the values are the frozen responses. The default behaviour is to only use the cache for requests where $request->is_idempotent is true (i.e., the dbh has the ReadOnly attribute set or the SQL statement is obviously a SELECT without a FOR UPDATE clause.) For even more control you can use the C attribute to pass in an instantiated cache object. Individual methods, including prepare(), can also specify alternative caches via the C attribute. For example, to specify no caching for a particular query, you could use $sth = $dbh->prepare( $sql, { go_cache => 0 } ); This can be used to implement different caching policies for different statements. It's interesting to note that DBD::Gofer can be used to add client-side caching to any (gofer compatible) application, with no code changes and no need for a gofer server. Just set the DBI_AUTOPROXY environment variable like this: DBI_AUTOPROXY='dbi:Gofer:transport=null;cache=1' =head1 CONFIGURING BEHAVIOUR POLICY DBD::Gofer supports a 'policy' mechanism that allows you to fine-tune the number of round-trips to the Gofer server. The policies are grouped into classes (which may be subclassed) and referenced by the name of the class. The L class is the base class for all the policy packages and describes all the available policies. Three policy packages are supplied with DBD::Gofer: L is most 'transparent' but slowest because it makes more round-trips to the Gofer server. L is a reasonable compromise - it's the default policy. L is fastest, but may require code changes in your applications. Generally the default C policy is fine. When first testing an existing application with Gofer it is a good idea to start with the C policy first and then switch to C or a custom policy, for final testing. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 ACKNOWLEDGEMENTS The development of DBD::Gofer and related modules was sponsored by Shopzilla.com (L), where I currently work. =head1 SEE ALSO L, L, L. L, L. L =head1 Caveats for specific drivers This section aims to record issues to be aware of when using Gofer with specific drivers. It usually only documents issues that are not natural consequences of the limitations of the Gofer approach - as documented above. =head1 TODO This is just a random brain dump... (There's more in the source of the Changes file, not the pod) Document policy mechanism Add mechanism for transports to list config params and for Gofer to apply any that match (and warn if any left over?) Driver-private sth attributes - set via prepare() - change DBI spec add hooks into transport base class for checking & updating a result set cache ie via a standard cache interface such as: http://search.cpan.org/~robm/Cache-FastMmap/FastMmap.pm http://search.cpan.org/~bradfitz/Cache-Memcached/lib/Cache/Memcached.pm http://search.cpan.org/~dclinton/Cache-Cache/ http://search.cpan.org/~cleishman/Cache/ Also caching instructions could be passed through the httpd transport layer in such a way that appropriate http cache headers are added to the results so that web caches (squid etc) could be used to implement the caching. (MUST require the use of GET rather than POST requests.) Rework handling of installed_methods to not piggyback on dbh_attributes? Perhaps support transactions for transports where it's possible (ie null and stream)? Would make stream transport (ie ssh) more useful to more people. Make sth_result_attr more like dbh_attributes (using '*' etc) Add @val = FETCH_many(@names) to DBI in C and use in Gofer/Execute? Implement _new_sth in C. =cut PK1]7LNullP.pmnu[use strict; { package DBD::NullP; require DBI; require Carp; our @EXPORT = qw(); # Do NOT @EXPORT anything. our $VERSION = "12.014715"; # $Id: NullP.pm 14714 2011-02-22 17:27:07Z Tim $ # # Copyright (c) 1994-2007 Tim Bunce # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. our $drh = undef; # holds driver handle once initialised sub driver{ return $drh if $drh; my($class, $attr) = @_; $class .= "::dr"; ($drh) = DBI::_new_drh($class, { 'Name' => 'NullP', 'Version' => $VERSION, 'Attribution' => 'DBD Example Null Perl stub by Tim Bunce', }, [ qw'example implementors private data']); $drh; } sub CLONE { undef $drh; } } { package DBD::NullP::dr; # ====== DRIVER ====== our $imp_data_size = 0; use strict; sub connect { # normally overridden, but a handy default my $dbh = shift->SUPER::connect(@_) or return; $dbh->STORE(Active => 1); $dbh; } sub DESTROY { undef } } { package DBD::NullP::db; # ====== DATABASE ====== our $imp_data_size = 0; use strict; use Carp qw(croak); # Added get_info to support tests in 10examp.t sub get_info { my ($dbh, $type) = @_; if ($type == 29) { # identifier quote return '"'; } return; } # Added table_info to support tests in 10examp.t sub table_info { my ($dbh, $catalog, $schema, $table, $type) = @_; my ($outer, $sth) = DBI::_new_sth($dbh, { 'Statement' => 'tables', }); if (defined($type) && $type eq '%' && # special case for tables('','','','%') grep {defined($_) && $_ eq ''} ($catalog, $schema, $table)) { $outer->{dbd_nullp_data} = [[undef, undef, undef, 'TABLE', undef], [undef, undef, undef, 'VIEW', undef], [undef, undef, undef, 'ALIAS', undef]]; } elsif (defined($catalog) && $catalog eq '%' && # special case for tables('%','','') grep {defined($_) && $_ eq ''} ($schema, $table)) { $outer->{dbd_nullp_data} = [['catalog1', undef, undef, undef, undef], ['catalog2', undef, undef, undef, undef]]; } else { $outer->{dbd_nullp_data} = [['catalog', 'schema', 'table1', 'TABLE']]; $outer->{dbd_nullp_data} = [['catalog', 'schema', 'table2', 'TABLE']]; $outer->{dbd_nullp_data} = [['catalog', 'schema', 'table3', 'TABLE']]; } $outer->STORE(NUM_OF_FIELDS => 5); $sth->STORE(Active => 1); return $outer; } sub prepare { my ($dbh, $statement)= @_; my ($outer, $sth) = DBI::_new_sth($dbh, { 'Statement' => $statement, }); return $outer; } sub FETCH { my ($dbh, $attrib) = @_; # In reality this would interrogate the database engine to # either return dynamic values that cannot be precomputed # or fetch and cache attribute values too expensive to prefetch. return $dbh->SUPER::FETCH($attrib); } sub STORE { my ($dbh, $attrib, $value) = @_; # would normally validate and only store known attributes # else pass up to DBI to handle if ($attrib eq 'AutoCommit') { Carp::croak("Can't disable AutoCommit") unless $value; # convert AutoCommit values to magic ones to let DBI # know that the driver has 'handled' the AutoCommit attribute $value = ($value) ? -901 : -900; } elsif ($attrib eq 'nullp_set_err') { # a fake attribute to produce a test case where STORE issues a warning $dbh->set_err($value, $value); } return $dbh->SUPER::STORE($attrib, $value); } sub ping { 1 } sub disconnect { shift->STORE(Active => 0); } } { package DBD::NullP::st; # ====== STATEMENT ====== our $imp_data_size = 0; use strict; sub bind_param { my ($sth, $param, $value, $attr) = @_; $sth->{ParamValues}{$param} = $value; $sth->{ParamAttr}{$param} = $attr if defined $attr; # attr is sticky if not explicitly set return 1; } sub execute { my $sth = shift; $sth->bind_param($_, $_[$_-1]) for (1..@_); if ($sth->{Statement} =~ m/^ \s* SELECT \s+/xmsi) { $sth->STORE(NUM_OF_FIELDS => 1); $sth->{NAME} = [ "fieldname" ]; # just for the sake of returning something, we return the params my $params = $sth->{ParamValues} || {}; $sth->{dbd_nullp_data} = [ @{$params}{ sort keys %$params } ]; $sth->STORE(Active => 1); } # force a sleep - handy for testing elsif ($sth->{Statement} =~ m/^ \s* SLEEP \s+ (\S+) /xmsi) { my $secs = $1; if (eval { require Time::HiRes; defined &Time::HiRes::sleep }) { Time::HiRes::sleep($secs); } else { sleep $secs; } } # force an error - handy for testing elsif ($sth->{Statement} =~ m/^ \s* ERROR \s+ (\d+) \s* (.*) /xmsi) { return $sth->set_err($1, $2); } # anything else is silently ignored, successfully 1; } sub fetchrow_arrayref { my $sth = shift; my $data = shift @{$sth->{dbd_nullp_data}}; if (!$data || !@$data) { $sth->finish; # no more data so finish return undef; } return $sth->_set_fbav($data); } *fetch = \&fetchrow_arrayref; # alias sub FETCH { my ($sth, $attrib) = @_; # would normally validate and only fetch known attributes # else pass up to DBI to handle return $sth->SUPER::FETCH($attrib); } sub STORE { my ($sth, $attrib, $value) = @_; # would normally validate and only store known attributes # else pass up to DBI to handle return $sth->SUPER::STORE($attrib, $value); } } 1; PK1]"CM''Mem.pmnu[# -*- perl -*- # # DBD::Mem - A DBI driver for in-memory tables # # This module is currently maintained by # # Jens Rehsack # # Copyright (C) 2016,2017 by Jens Rehsack # # All rights reserved. # # You may distribute this module under the terms of either the GNU # General Public License or the Artistic License, as specified in # the Perl README file. require 5.008; use strict; ################# package DBD::Mem; ################# use base qw( DBI::DBD::SqlEngine ); use vars qw($VERSION $ATTRIBUTION $drh); $VERSION = '0.001'; $ATTRIBUTION = 'DBD::Mem by Jens Rehsack'; # no need to have driver() unless you need private methods # sub driver ($;$) { my ( $class, $attr ) = @_; return $drh if ($drh); # do the real work in DBI::DBD::SqlEngine # $attr->{Attribution} = 'DBD::Mem by Jens Rehsack'; $drh = $class->SUPER::driver($attr); return $drh; } sub CLONE { undef $drh; } ##################### package DBD::Mem::dr; ##################### $DBD::Mem::dr::imp_data_size = 0; @DBD::Mem::dr::ISA = qw(DBI::DBD::SqlEngine::dr); # you could put some :dr private methods here # you may need to over-ride some DBI::DBD::SqlEngine::dr methods here # but you can probably get away with just letting it do the work # in most cases ##################### package DBD::Mem::db; ##################### $DBD::Mem::db::imp_data_size = 0; @DBD::Mem::db::ISA = qw(DBI::DBD::SqlEngine::db); use Carp qw/carp/; sub set_versions { my $this = $_[0]; $this->{mem_version} = $DBD::Mem::VERSION; return $this->SUPER::set_versions(); } sub init_valid_attributes { my $dbh = shift; # define valid private attributes # # attempts to set non-valid attrs in connect() or # with $dbh->{attr} will throw errors # # the attrs here *must* start with mem_ or foo_ # # see the STORE methods below for how to check these attrs # $dbh->{mem_valid_attrs} = { mem_version => 1, # verbose DBD::Mem version mem_valid_attrs => 1, # DBD::Mem::db valid attrs mem_readonly_attrs => 1, # DBD::Mem::db r/o attrs mem_meta => 1, # DBD::Mem public access for f_meta mem_tables => 1, # DBD::Mem public access for f_meta }; $dbh->{mem_readonly_attrs} = { mem_version => 1, # verbose DBD::Mem version mem_valid_attrs => 1, # DBD::Mem::db valid attrs mem_readonly_attrs => 1, # DBD::Mem::db r/o attrs mem_meta => 1, # DBD::Mem public access for f_meta }; $dbh->{mem_meta} = "mem_tables"; return $dbh->SUPER::init_valid_attributes(); } sub get_mem_versions { my ( $dbh, $table ) = @_; $table ||= ''; my $meta; my $class = $dbh->{ImplementorClass}; $class =~ s/::db$/::Table/; $table and ( undef, $meta ) = $class->get_table_meta( $dbh, $table, 1 ); $meta or ( $meta = {} and $class->bootstrap_table_meta( $dbh, $meta, $table ) ); return sprintf( "%s using %s", $dbh->{mem_version}, $AnyData2::VERSION ); } package DBD::Mem::st; use strict; use warnings; our $imp_data_size = 0; our @ISA = qw(DBI::DBD::SqlEngine::st); ############################ package DBD::Mem::Statement; ############################ @DBD::Mem::Statement::ISA = qw(DBI::DBD::SqlEngine::Statement); sub open_table ($$$$$) { my ( $self, $data, $table, $createMode, $lockMode ) = @_; my $class = ref $self; $class =~ s/::Statement/::Table/; my $flags = { createMode => $createMode, lockMode => $lockMode, }; if( defined( $data->{Database}->{mem_table_data}->{$table} ) && $data->{Database}->{mem_table_data}->{$table}) { my $t = $data->{Database}->{mem_tables}->{$table}; $t->seek( $data, 0, 0 ); return $t; } return $self->SUPER::open_table($data, $table, $createMode, $lockMode); } # ====== DataSource ============================================================ package DBD::Mem::DataSource; use strict; use warnings; use Carp; @DBD::Mem::DataSource::ISA = "DBI::DBD::SqlEngine::DataSource"; sub complete_table_name ($$;$) { my ( $self, $meta, $table, $respect_case ) = @_; $table; } sub open_data ($) { my ( $self, $meta, $attrs, $flags ) = @_; defined $meta->{data_tbl} or $meta->{data_tbl} = []; } ######################## package DBD::Mem::Table; ######################## # shamelessly stolen from SQL::Statement::RAM use Carp qw/croak/; @DBD::Mem::Table::ISA = qw(DBI::DBD::SqlEngine::Table); use Carp qw(croak); sub new { #my ( $class, $tname, $col_names, $data_tbl ) = @_; my ( $class, $data, $attrs, $flags ) = @_; my $self = $class->SUPER::new($data, $attrs, $flags); my $meta = $self->{meta}; $self->{records} = $meta->{data_tbl}; $self->{index} = 0; $self; } sub bootstrap_table_meta { my ( $self, $dbh, $meta, $table ) = @_; defined $meta->{sql_data_source} or $meta->{sql_data_source} = "DBD::Mem::DataSource"; $meta; } sub fetch_row { my ( $self, $data ) = @_; return $self->{row} = ( $self->{records} and ( $self->{index} < scalar( @{ $self->{records} } ) ) ) ? [ @{ $self->{records}->[ $self->{index}++ ] } ] : undef; } sub push_row { my ( $self, $data, $fields ) = @_; my $currentRow = $self->{index}; $self->{index} = $currentRow + 1; $self->{records}->[$currentRow] = $fields; return 1; } sub truncate { my $self = shift; return splice @{ $self->{records} }, $self->{index}, 1; } sub push_names { my ( $self, $data, $names ) = @_; my $meta = $self->{meta}; $meta->{col_names} = $self->{col_names} = $names; $self->{org_col_names} = [ @{$names} ]; $self->{col_nums} = {}; $self->{col_nums}{ $names->[$_] } = $_ for ( 0 .. scalar @$names - 1 ); } sub drop ($) { my ($self, $data) = @_; delete $data->{Database}{sql_meta}{$self->{table}}; return 1; } # drop sub seek { my ( $self, $data, $pos, $whence ) = @_; return unless defined $self->{records}; my ($currentRow) = $self->{index}; if ( $whence == 0 ) { $currentRow = $pos; } elsif ( $whence == 1 ) { $currentRow += $pos; } elsif ( $whence == 2 ) { $currentRow = @{ $self->{records} } + $pos; } else { croak $self . "->seek: Illegal whence argument ($whence)"; } $currentRow < 0 and croak "Illegal row number: $currentRow"; $self->{index} = $currentRow; } 1; =head1 NAME DBD::Mem - a DBI driver for Mem & MLMem files =head1 SYNOPSIS use DBI; $dbh = DBI->connect('dbi:Mem:', undef, undef, {}); $dbh = DBI->connect('dbi:Mem:', undef, undef, {RaiseError => 1}); # or $dbh = DBI->connect('dbi:Mem:'); $dbh = DBI->connect('DBI:Mem(RaiseError=1):'); and other variations on connect() as shown in the L docs and . Use standard DBI prepare, execute, fetch, placeholders, etc., see L for an example. =head1 DESCRIPTION DBD::Mem is a database management system that works right out of the box. If you have a standard installation of Perl and DBI you can begin creating, accessing, and modifying simple database tables without any further modules. You can add other modules (e.g., SQL::Statement) for improved functionality. DBD::Mem doesn't store any data persistently - all data has the lifetime of the instantiated C<$dbh>. The main reason to use DBD::Mem is to use extended features of L where temporary tables are required. One can use DBD::Mem to simulate C or sub-queries. Bundling C with L will allow us further compatibility checks of L beyond the capabilities of L and L. This will ensure DBI provided basis for drivers like L or L are better prepared and tested for not-file based backends. =head2 Metadata There're no new meta data introduced by C. See L for full description. =head1 GETTING HELP, MAKING SUGGESTIONS, AND REPORTING BUGS If you need help installing or using DBD::Mem, please write to the DBI users mailing list at L or to the comp.lang.perl.modules newsgroup on usenet. I cannot always answer every question quickly but there are many on the mailing list or in the newsgroup who can. DBD developers for DBD's which rely on DBI::DBD::SqlEngine or DBD::Mem or use one of them as an example are suggested to join the DBI developers mailing list at L and strongly encouraged to join our IRC channel at L. If you have suggestions, ideas for improvements, or bugs to report, please report a bug as described in DBI. Do not mail any of the authors directly, you might not get an answer. When reporting bugs, please send the output of C<< $dbh->mem_versions($table) >> for a table that exhibits the bug and as small a sample as you can make of the code that produces the bug. And of course, patches are welcome, too :-). If you need enhancements quickly, you can get commercial support as described at L or you can contact Jens Rehsack at rehsack@cpan.org for commercial support. =head1 AUTHOR AND COPYRIGHT This module is written by Jens Rehsack < rehsack AT cpan.org >. Copyright (c) 2016- by Jens Rehsack, all rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =head1 SEE ALSO L for the Database interface of the Perl Programming Language. L and L for the available SQL engines. L where the implementation is shamelessly stolen from to allow DBI bundled Pure-Perl drivers increase the test coverage. L using C for an incredible fast in-memory database engine. =cut PK1] DۃGofer/Transport/pipeone.pmnu[package DBD::Gofer::Transport::pipeone; # $Id: pipeone.pm 10087 2007-10-16 12:42:37Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; use Carp; use Fcntl; use IO::Select; use IPC::Open3 qw(open3); use Symbol qw(gensym); use base qw(DBD::Gofer::Transport::Base); our $VERSION = "0.010088"; __PACKAGE__->mk_accessors(qw( connection_info go_perl )); sub new { my ($self, $args) = @_; $args->{go_perl} ||= do { ($INC{"blib.pm"}) ? [ $^X, '-Mblib' ] : [ $^X ]; }; if (not ref $args->{go_perl}) { # user can override the perl to be used, either with an array ref # containing the command name and args to use, or with a string # (ie via the DSN) in which case, to enable args to be passed, # we split on two or more consecutive spaces (otherwise the path # to perl couldn't contain a space itself). $args->{go_perl} = [ split /\s{2,}/, $args->{go_perl} ]; } return $self->SUPER::new($args); } # nonblock($fh) puts filehandle into nonblocking mode sub nonblock { my $fh = shift; my $flags = fcntl($fh, F_GETFL, 0) or croak "Can't get flags for filehandle $fh: $!"; fcntl($fh, F_SETFL, $flags | O_NONBLOCK) or croak "Can't make filehandle $fh nonblocking: $!"; } sub start_pipe_command { my ($self, $cmd) = @_; $cmd = [ $cmd ] unless ref $cmd eq 'ARRAY'; # if it's important that the subprocess uses the same # (versions of) modules as us then the caller should # set PERL5LIB itself. # limit various forms of insanity, for now local $ENV{DBI_TRACE}; # use DBI_GOFER_TRACE instead local $ENV{DBI_AUTOPROXY}; local $ENV{DBI_PROFILE}; my ($wfh, $rfh, $efh) = (gensym, gensym, gensym); my $pid = open3($wfh, $rfh, $efh, @$cmd) or die "error starting @$cmd: $!\n"; if ($self->trace) { $self->trace_msg(sprintf("Started pid $pid: @$cmd {fd: w%d r%d e%d, ppid=$$}\n", fileno $wfh, fileno $rfh, fileno $efh),0); } nonblock($rfh); nonblock($efh); my $ios = IO::Select->new($rfh, $efh); return { cmd=>$cmd, pid=>$pid, wfh=>$wfh, rfh=>$rfh, efh=>$efh, ios=>$ios, }; } sub cmd_as_string { my $self = shift; # XXX meant to return a properly shell-escaped string suitable for system # but its only for debugging so that can wait my $connection_info = $self->connection_info; return join " ", map { (m/^[-:\w]*$/) ? $_ : "'$_'" } @{$connection_info->{cmd}}; } sub transmit_request_by_transport { my ($self, $request) = @_; my $frozen_request = $self->freeze_request($request); my $cmd = [ @{$self->go_perl}, qw(-MDBI::Gofer::Transport::pipeone -e run_one_stdio)]; my $info = $self->start_pipe_command($cmd); my $wfh = delete $info->{wfh}; # send frozen request local $\; print $wfh $frozen_request or warn "error writing to @$cmd: $!\n"; # indicate that there's no more close $wfh or die "error closing pipe to @$cmd: $!\n"; $self->connection_info( $info ); return; } sub read_response_from_fh { my ($self, $fh_actions) = @_; my $trace = $self->trace; my $info = $self->connection_info || die; my ($ios) = @{$info}{qw(ios)}; my $errors = 0; my $complete; die "No handles to read response from" unless $ios->count; while ($ios->count) { my @readable = $ios->can_read(); for my $fh (@readable) { local $_; my $actions = $fh_actions->{$fh} || die "panic: no action for $fh"; my $rv = sysread($fh, $_='', 1024*31); # to fit in 32KB slab unless ($rv) { # error (undef) or end of file (0) my $action; unless (defined $rv) { # was an error $self->trace_msg("error on handle $fh: $!\n") if $trace >= 4; $action = $actions->{error} || $actions->{eof}; ++$errors; # XXX an error may be a permenent condition of the handle # if so we'll loop here - not good } else { $action = $actions->{eof}; $self->trace_msg("eof on handle $fh\n") if $trace >= 4; } if ($action->($fh)) { $self->trace_msg("removing $fh from handle set\n") if $trace >= 4; $ios->remove($fh); } next; } # action returns true if the response is now complete # (we finish all handles $actions->{read}->($fh) && ++$complete; } last if $complete; } return $errors; } sub receive_response_by_transport { my $self = shift; my $info = $self->connection_info || die; my ($pid, $rfh, $efh, $ios, $cmd) = @{$info}{qw(pid rfh efh ios cmd)}; my $frozen_response; my $stderr_msg; $self->read_response_from_fh( { $efh => { error => sub { warn "error reading response stderr: $!"; 1 }, eof => sub { warn "eof on stderr" if 0; 1 }, read => sub { $stderr_msg .= $_; 0 }, }, $rfh => { error => sub { warn "error reading response: $!"; 1 }, eof => sub { warn "eof on stdout" if 0; 1 }, read => sub { $frozen_response .= $_; 0 }, }, }); waitpid $info->{pid}, 0 or warn "waitpid: $!"; # XXX do something more useful? die ref($self)." command (@$cmd) failed: $stderr_msg" if not $frozen_response; # no output on stdout at all # XXX need to be able to detect and deal with corruption my $response = $self->thaw_response($frozen_response); if ($stderr_msg) { # add stderr messages as warnings (for PrintWarn) $response->add_err(0, $stderr_msg, undef, $self->trace) # but ignore warning from old version of blib unless $stderr_msg =~ /^Using .*blib/ && "@$cmd" =~ /-Mblib/; } return $response; } 1; __END__ =head1 NAME DBD::Gofer::Transport::pipeone - DBD::Gofer client transport for testing =head1 SYNOPSIS $original_dsn = "..."; DBI->connect("dbi:Gofer:transport=pipeone;dsn=$original_dsn",...) or, enable by setting the DBI_AUTOPROXY environment variable: export DBI_AUTOPROXY="dbi:Gofer:transport=pipeone" =head1 DESCRIPTION Connect via DBD::Gofer and execute each request by starting executing a subprocess. This is, as you might imagine, spectacularly inefficient! It's only intended for testing. Specifically it demonstrates that the server side is completely stateless. It also provides a base class for the much more useful L transport. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 SEE ALSO L L =cut PK1]+3 $ $Gofer/Transport/stream.pmnu[package DBD::Gofer::Transport::stream; # $Id: stream.pm 14598 2010-12-21 22:53:25Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; use Carp; use base qw(DBD::Gofer::Transport::pipeone); our $VERSION = "0.014599"; __PACKAGE__->mk_accessors(qw( go_persist )); my $persist_all = 5; my %persist; sub _connection_key { my ($self) = @_; return join "~", $self->go_url||"", @{ $self->go_perl || [] }; } sub _connection_get { my ($self) = @_; my $persist = $self->go_persist; # = 0 can force non-caching $persist = $persist_all if not defined $persist; my $key = ($persist) ? $self->_connection_key : ''; if ($persist{$key} && $self->_connection_check($persist{$key})) { $self->trace_msg("reusing persistent connection $key\n",0) if $self->trace >= 1; return $persist{$key}; } my $connection = $self->_make_connection; if ($key) { %persist = () if keys %persist > $persist_all; # XXX quick hack to limit subprocesses $persist{$key} = $connection; } return $connection; } sub _connection_check { my ($self, $connection) = @_; $connection ||= $self->connection_info; my $pid = $connection->{pid}; my $ok = (kill 0, $pid); $self->trace_msg("_connection_check: $ok (pid $$)\n",0) if $self->trace; return $ok; } sub _connection_kill { my ($self) = @_; my $connection = $self->connection_info; my ($pid, $wfh, $rfh, $efh) = @{$connection}{qw(pid wfh rfh efh)}; $self->trace_msg("_connection_kill: closing write handle\n",0) if $self->trace; # closing the write file handle should be enough, generally close $wfh; # in future we may want to be more aggressive #close $rfh; close $efh; kill 15, $pid # but deleting from the persist cache... delete $persist{ $self->_connection_key }; # ... and removing the connection_info should suffice $self->connection_info( undef ); return; } sub _make_connection { my ($self) = @_; my $go_perl = $self->go_perl; my $cmd = [ @$go_perl, qw(-MDBI::Gofer::Transport::stream -e run_stdio_hex)]; #push @$cmd, "DBI_TRACE=2=/tmp/goferstream.log", "sh", "-c"; if (my $url = $self->go_url) { die "Only 'ssh:user\@host' style url supported by this transport" unless $url =~ s/^ssh://; my $ssh = $url; my $setup_env = join "||", map { "source $_ 2>/dev/null" } qw(.bash_profile .bash_login .profile); my $setup = $setup_env.q{; exec "$@"}; # don't use $^X on remote system by default as it's possibly wrong $cmd->[0] = 'perl' if "@$go_perl" eq $^X; # -x not only 'Disables X11 forwarding' but also makes connections *much* faster unshift @$cmd, qw(ssh -xq), split(' ', $ssh), qw(bash -c), $setup; } $self->trace_msg("new connection: @$cmd\n",0) if $self->trace; # XXX add a handshake - some message from DBI::Gofer::Transport::stream that's # sent as soon as it starts that we can wait for to report success - and soak up # and report useful warnings etc from ssh before we get it? Increases latency though. my $connection = $self->start_pipe_command($cmd); return $connection; } sub transmit_request_by_transport { my ($self, $request) = @_; my $trace = $self->trace; my $connection = $self->connection_info || do { my $con = $self->_connection_get; $self->connection_info( $con ); $con; }; my $encoded_request = unpack("H*", $self->freeze_request($request)); $encoded_request .= "\015\012"; my $wfh = $connection->{wfh}; $self->trace_msg(sprintf("transmit_request_by_transport: to fh %s fd%d\n", $wfh, fileno($wfh)),0) if $trace >= 4; # send frozen request local $\; $wfh->print($encoded_request) # autoflush enabled or do { my $err = $!; # XXX could/should make new connection and retry $self->_connection_kill; die "Error sending request: $err"; }; $self->trace_msg("Request sent: $encoded_request\n",0) if $trace >= 4; return undef; # indicate no response yet (so caller calls receive_response_by_transport) } sub receive_response_by_transport { my $self = shift; my $trace = $self->trace; $self->trace_msg("receive_response_by_transport: awaiting response\n",0) if $trace >= 4; my $connection = $self->connection_info || die; my ($pid, $rfh, $efh, $cmd) = @{$connection}{qw(pid rfh efh cmd)}; my $errno = 0; my $encoded_response; my $stderr_msg; $self->read_response_from_fh( { $efh => { error => sub { warn "error reading response stderr: $!"; $errno||=$!; 1 }, eof => sub { warn "eof reading efh" if $trace >= 4; 1 }, read => sub { $stderr_msg .= $_; 0 }, }, $rfh => { error => sub { warn "error reading response: $!"; $errno||=$!; 1 }, eof => sub { warn "eof reading rfh" if $trace >= 4; 1 }, read => sub { $encoded_response .= $_; ($encoded_response=~s/\015\012$//) ? 1 : 0 }, }, }); # if we got no output on stdout at all then the command has # probably exited, possibly with an error to stderr. # Turn this situation into a reasonably useful DBI error. if (not $encoded_response) { my @msg; push @msg, "error while reading response: $errno" if $errno; if ($stderr_msg) { chomp $stderr_msg; push @msg, sprintf "error reported by \"%s\" (pid %d%s): %s", $self->cmd_as_string, $pid, ((kill 0, $pid) ? "" : ", exited"), $stderr_msg; } die join(", ", "No response received", @msg)."\n"; } $self->trace_msg("Response received: $encoded_response\n",0) if $trace >= 4; $self->trace_msg("Gofer stream stderr message: $stderr_msg\n",0) if $stderr_msg && $trace; my $frozen_response = pack("H*", $encoded_response); # XXX need to be able to detect and deal with corruption my $response = $self->thaw_response($frozen_response); if ($stderr_msg) { # add stderr messages as warnings (for PrintWarn) $response->add_err(0, $stderr_msg, undef, $trace) # but ignore warning from old version of blib unless $stderr_msg =~ /^Using .*blib/ && "@$cmd" =~ /-Mblib/; } return $response; } sub transport_timedout { my $self = shift; $self->_connection_kill; return $self->SUPER::transport_timedout(@_); } 1; __END__ =head1 NAME DBD::Gofer::Transport::stream - DBD::Gofer transport for stdio streaming =head1 SYNOPSIS DBI->connect('dbi:Gofer:transport=stream;url=ssh:username@host.example.com;dsn=dbi:...',...) or, enable by setting the DBI_AUTOPROXY environment variable: export DBI_AUTOPROXY='dbi:Gofer:transport=stream;url=ssh:username@host.example.com' =head1 DESCRIPTION Without the C parameter it launches a subprocess as perl -MDBI::Gofer::Transport::stream -e run_stdio_hex and feeds requests into it and reads responses from it. But that's not very useful. With a C parameter it uses ssh to launch the subprocess on a remote system. That's much more useful! It gives you secure remote access to DBI databases on any system you can login to. Using ssh also gives you optional compression and many other features (see the ssh manual for how to configure that and many other options via ~/.ssh/config file). The actual command invoked is something like: ssh -xq ssh:username@host.example.com bash -c $setup $run where $run is the command shown above, and $command is . .bash_profile 2>/dev/null || . .bash_login 2>/dev/null || . .profile 2>/dev/null; exec "$@" which is trying (in a limited and fairly unportable way) to setup the environment (PATH, PERL5LIB etc) as it would be if you had logged in to that system. The "C" used in the command will default to the value of $^X when not using ssh. On most systems that's the full path to the perl that's currently executing. =head1 PERSISTENCE Currently gofer stream connections persist (remain connected) after all database handles have been disconnected. This makes later connections in the same process very fast. Currently up to 5 different gofer stream connections (based on url) can persist. If more than 5 are in the cache when a new connection is made then the cache is cleared before adding the new connection. Simple but effective. =head1 TO DO Document go_perl attribute Automatically reconnect (within reason) if there's a transport error. Decide on default for persistent connection - on or off? limits? ttl? =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 SEE ALSO L L =cut PK1]]Ïr Gofer/Transport/null.pmnu[package DBD::Gofer::Transport::null; # $Id: null.pm 10087 2007-10-16 12:42:37Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; use base qw(DBD::Gofer::Transport::Base); use DBI::Gofer::Execute; our $VERSION = "0.010088"; __PACKAGE__->mk_accessors(qw( pending_response transmit_count )); my $executor = DBI::Gofer::Execute->new(); sub transmit_request_by_transport { my ($self, $request) = @_; $self->transmit_count( ($self->transmit_count()||0) + 1 ); # just for tests my $frozen_request = $self->freeze_request($request); # ... # the request is magically transported over to ... ourselves # ... my $response = $executor->execute_request( $self->thaw_request($frozen_request, undef, 1) ); # put response 'on the shelf' ready for receive_response() $self->pending_response( $response ); return undef; } sub receive_response_by_transport { my $self = shift; my $response = $self->pending_response; my $frozen_response = $self->freeze_response($response, undef, 1); # ... # the response is magically transported back to ... ourselves # ... return $self->thaw_response($frozen_response); } 1; __END__ =head1 NAME DBD::Gofer::Transport::null - DBD::Gofer client transport for testing =head1 SYNOPSIS my $original_dsn = "..." DBI->connect("dbi:Gofer:transport=null;dsn=$original_dsn",...) or, enable by setting the DBI_AUTOPROXY environment variable: export DBI_AUTOPROXY="dbi:Gofer:transport=null" =head1 DESCRIPTION Connect via DBD::Gofer but execute the requests within the same process. This is a quick and simple way to test applications for compatibility with the (few) restrictions that DBD::Gofer imposes. It also provides a simple, portable way for the DBI test suite to be used to test DBD::Gofer on all platforms with no setup. Also, by measuring the difference in performance between normal connections and connections via C the basic cost of using DBD::Gofer can be measured. Furthermore, the additional cost of more advanced transports can be isolated by comparing their performance with the null transport. The C script in the DBI distribution includes a comparative benchmark. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 SEE ALSO L L =cut PK1]=o11Gofer/Transport/Base.pmnu[package DBD::Gofer::Transport::Base; # $Id: Base.pm 14120 2010-06-07 19:52:19Z H.Merijn $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; use base qw(DBI::Gofer::Transport::Base); our $VERSION = "0.014121"; __PACKAGE__->mk_accessors(qw( trace go_dsn go_url go_policy go_timeout go_retry_hook go_retry_limit go_cache cache_hit cache_miss cache_store )); __PACKAGE__->mk_accessors_using(make_accessor_autoviv_hashref => qw( meta )); sub new { my ($class, $args) = @_; $args->{$_} = 0 for (qw(cache_hit cache_miss cache_store)); $args->{keep_meta_frozen} ||= 1 if $args->{go_cache}; #warn "args @{[ %$args ]}\n"; return $class->SUPER::new($args); } sub _init_trace { $ENV{DBD_GOFER_TRACE} || 0 } sub new_response { my $self = shift; return DBI::Gofer::Response->new(@_); } sub transmit_request { my ($self, $request) = @_; my $trace = $self->trace; my $response; my ($go_cache, $request_cache_key); if ($go_cache = $self->{go_cache}) { $request_cache_key = $request->{meta}{request_cache_key} = $self->get_cache_key_for_request($request); if ($request_cache_key) { my $frozen_response = eval { $go_cache->get($request_cache_key) }; if ($frozen_response) { $self->_dump("cached response found for ".ref($request), $request) if $trace; $response = $self->thaw_response($frozen_response); $self->trace_msg("transmit_request is returning a response from cache $go_cache\n") if $trace; ++$self->{cache_hit}; return $response; } warn $@ if $@; ++$self->{cache_miss}; $self->trace_msg("transmit_request cache miss\n") if $trace; } } my $to = $self->go_timeout; my $transmit_sub = sub { $self->trace_msg("transmit_request\n") if $trace; local $SIG{ALRM} = sub { die "TIMEOUT\n" } if $to; my $response = eval { local $SIG{PIPE} = sub { my $extra = ($! eq "Broken pipe") ? "" : " ($!)"; die "Unable to send request: Broken pipe$extra\n"; }; alarm($to) if $to; $self->transmit_request_by_transport($request); }; alarm(0) if $to; if ($@) { return $self->transport_timedout("transmit_request", $to) if $@ eq "TIMEOUT\n"; return $self->new_response({ err => 1, errstr => $@ }); } return $response; }; $response = $self->_transmit_request_with_retries($request, $transmit_sub); if ($response) { my $frozen_response = delete $response->{meta}{frozen}; $self->_store_response_in_cache($frozen_response, $request_cache_key) if $request_cache_key; } $self->trace_msg("transmit_request is returning a response itself\n") if $trace && $response; return $response unless wantarray; return ($response, $transmit_sub); } sub _transmit_request_with_retries { my ($self, $request, $transmit_sub) = @_; my $response; do { $response = $transmit_sub->(); } while ( $response && $self->response_needs_retransmit($request, $response) ); return $response; } sub receive_response { my ($self, $request, $retransmit_sub) = @_; my $to = $self->go_timeout; my $receive_sub = sub { $self->trace_msg("receive_response\n"); local $SIG{ALRM} = sub { die "TIMEOUT\n" } if $to; my $response = eval { alarm($to) if $to; $self->receive_response_by_transport($request); }; alarm(0) if $to; if ($@) { return $self->transport_timedout("receive_response", $to) if $@ eq "TIMEOUT\n"; return $self->new_response({ err => 1, errstr => $@ }); } return $response; }; my $response; do { $response = $receive_sub->(); if ($self->response_needs_retransmit($request, $response)) { $response = $self->_transmit_request_with_retries($request, $retransmit_sub); $response ||= $receive_sub->(); } } while ( $self->response_needs_retransmit($request, $response) ); if ($response) { my $frozen_response = delete $response->{meta}{frozen}; my $request_cache_key = $request->{meta}{request_cache_key}; $self->_store_response_in_cache($frozen_response, $request_cache_key) if $request_cache_key && $self->{go_cache}; } return $response; } sub response_retry_preference { my ($self, $request, $response) = @_; # give the user a chance to express a preference (or undef for default) if (my $go_retry_hook = $self->go_retry_hook) { my $retry = $go_retry_hook->($request, $response, $self); $self->trace_msg(sprintf "go_retry_hook returned %s\n", (defined $retry) ? $retry : 'undef'); return $retry if defined $retry; } # This is the main decision point. We don't retry requests that got # as far as executing because the error is probably from the database # (not transport) so retrying is unlikely to help. But note that any # severe transport error occurring after execute is likely to return # a new response object that doesn't have the execute flag set. Beware! return 0 if $response->executed_flag_set; return 1 if ($response->errstr || '') =~ m/induced by DBI_GOFER_RANDOM/; return 1 if $request->is_idempotent; # i.e. is SELECT or ReadOnly was set return undef; # we couldn't make up our mind } sub response_needs_retransmit { my ($self, $request, $response) = @_; my $err = $response->err or return 0; # nothing went wrong my $retry = $self->response_retry_preference($request, $response); if (!$retry) { # false or undef $self->trace_msg("response_needs_retransmit: response not suitable for retry\n"); return 0; } # we'd like to retry but have we retried too much already? my $retry_limit = $self->go_retry_limit; if (!$retry_limit) { $self->trace_msg("response_needs_retransmit: retries disabled (retry_limit not set)\n"); return 0; } my $request_meta = $request->meta; my $retry_count = $request_meta->{retry_count} || 0; if ($retry_count >= $retry_limit) { $self->trace_msg("response_needs_retransmit: $retry_count is too many retries\n"); # XXX should be possible to disable altering the err $response->errstr(sprintf "%s (after %d retries by gofer)", $response->errstr, $retry_count); return 0; } # will retry now, do the admin ++$retry_count; $self->trace_msg("response_needs_retransmit: retry $retry_count\n"); # hook so response_retry_preference can defer some code execution # until we've checked retry_count and retry_limit. if (ref $retry eq 'CODE') { $retry->($retry_count, $retry_limit) and warn "should return false"; # protect future use } ++$request_meta->{retry_count}; # update count for this request object ++$self->meta->{request_retry_count}; # update cumulative transport stats return 1; } sub transport_timedout { my ($self, $method, $timeout) = @_; $timeout ||= $self->go_timeout; return $self->new_response({ err => 1, errstr => "DBD::Gofer $method timed-out after $timeout seconds" }); } # return undef if we don't want to cache this request # subclasses may use more specialized rules sub get_cache_key_for_request { my ($self, $request) = @_; # we only want to cache idempotent requests # is_idempotent() is true if GOf_REQUEST_IDEMPOTENT or GOf_REQUEST_READONLY set return undef if not $request->is_idempotent; # XXX would be nice to avoid the extra freeze here my $key = $self->freeze_request($request, undef, 1); #use Digest::MD5; warn "get_cache_key_for_request: ".Digest::MD5::md5_base64($key)."\n"; return $key; } sub _store_response_in_cache { my ($self, $frozen_response, $request_cache_key) = @_; my $go_cache = $self->{go_cache} or return; # new() ensures that enabling go_cache also enables keep_meta_frozen warn "No meta frozen in response" if !$frozen_response; warn "No request_cache_key" if !$request_cache_key; if ($frozen_response && $request_cache_key) { $self->trace_msg("receive_response added response to cache $go_cache\n"); eval { $go_cache->set($request_cache_key, $frozen_response) }; warn $@ if $@; ++$self->{cache_store}; } } 1; __END__ =head1 NAME DBD::Gofer::Transport::Base - base class for DBD::Gofer client transports =head1 SYNOPSIS my $remote_dsn = "..." DBI->connect("dbi:Gofer:transport=...;url=...;timeout=...;retry_limit=...;dsn=$remote_dsn",...) or, enable by setting the DBI_AUTOPROXY environment variable: export DBI_AUTOPROXY='dbi:Gofer:transport=...;url=...' which will force I DBI connections to be made via that Gofer server. =head1 DESCRIPTION This is the base class for all DBD::Gofer client transports. =head1 ATTRIBUTES Gofer transport attributes can be specified either in the attributes parameter of the connect() method call, or in the DSN string. When used in the DSN string, attribute names don't have the C prefix. =head2 go_dsn The full DBI DSN that the Gofer server should connect to on your behalf. When used in the DSN it must be the last element in the DSN string. =head2 go_timeout A time limit for sending a request and receiving a response. Some drivers may implement sending and receiving as separate steps, in which case (currently) the timeout applies to each separately. If a request needs to be resent then the timeout is restarted for each sending of a request and receiving of a response. =head2 go_retry_limit The maximum number of times an request may be retried. The default is 2. =head2 go_retry_hook This subroutine reference is called, if defined, for each response received where $response->err is true. The subroutine is pass three parameters: the request object, the response object, and the transport object. If it returns an undefined value then the default retry behaviour is used. See L below. If it returns a defined but false value then the request is not resent. If it returns true value then the request is resent, so long as the number of retries does not exceed C. =head1 RETRY ON ERROR The default retry on error behaviour is: - Retry if the error was due to DBI_GOFER_RANDOM. See L. - Retry if $request->is_idempotent returns true. See L. A retry won't be allowed if the number of previous retries has reached C. =head1 TRACING Tracing of gofer requests and responses can be enabled by setting the C environment variable. A value of 1 gives a reasonably compact summary of each request and response. A value of 2 or more gives a detailed, and voluminous, dump. The trace is written using DBI->trace_msg() and so is written to the default DBI trace output, which is usually STDERR. =head1 METHODS I =head2 response_retry_preference $retry = $transport->response_retry_preference($request, $response); The response_retry_preference is called by DBD::Gofer when considering if a request should be retried after an error. Returns true (would like to retry), false (must not retry), undef (no preference). If a true value is returned in the form of a CODE ref then, if DBD::Gofer does decide to retry the request, it calls the code ref passing $retry_count, $retry_limit. Can be used for logging and/or to implement exponential backoff behaviour. Currently the called code must return using C to allow for future extensions. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007-2008, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 SEE ALSO L, L, L, L. and some example transports: L L L =cut PK1]_Gofer/Policy/pedantic.pmnu[package DBD::Gofer::Policy::pedantic; # $Id: pedantic.pm 10087 2007-10-16 12:42:37Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; our $VERSION = "0.010088"; use base qw(DBD::Gofer::Policy::Base); # the 'pedantic' policy is the same as the Base policy 1; =head1 NAME DBD::Gofer::Policy::pedantic - The 'pedantic' policy for DBD::Gofer =head1 SYNOPSIS $dbh = DBI->connect("dbi:Gofer:transport=...;policy=pedantic", ...) =head1 DESCRIPTION The C policy tries to be as transparent as possible. To do this it makes round-trips to the server for almost every DBI method call. This is the best policy to use when first testing existing code with Gofer. Once it's working well you should consider moving to the C policy or defining your own policy class. Temporary docs: See the source code for list of policies and their defaults. In a future version the policies and their defaults will be defined in the pod and parsed out at load-time. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =cut PK1]3<ȍ% % Gofer/Policy/rush.pmnu[package DBD::Gofer::Policy::rush; # $Id: rush.pm 10087 2007-10-16 12:42:37Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; our $VERSION = "0.010088"; use base qw(DBD::Gofer::Policy::Base); __PACKAGE__->create_policy_subs({ # always use connect_cached on server connect_method => 'connect_cached', # use same methods on server as is called on client # (because code not using placeholders would bloat the sth cache) prepare_method => '', # Skipping the connect check is fast, but it also skips # fetching the remote dbh attributes! # Make sure that your application doesn't need access to dbh attributes. skip_connect_check => 1, # most code doesn't rely on sth attributes being set after prepare skip_prepare_check => 1, # we're happy to use local method if that's the same as the remote skip_default_methods => 1, # ping is almost meaningless for DBD::Gofer and most transports anyway skip_ping => 1, # don't update dbh attributes at all # XXX actually we currently need dbh_attribute_update for skip_default_methods to work # and skip_default_methods is more valuable to us than the cost of dbh_attribute_update dbh_attribute_update => 'none', # actually means 'first' currently #dbh_attribute_list => undef, # we'd like to set locally_* but can't because drivers differ # in a rush assume metadata doesn't change cache_tables => 1, cache_table_info => 1, cache_column_info => 1, cache_primary_key_info => 1, cache_foreign_key_info => 1, cache_statistics_info => 1, cache_get_info => 1, }); 1; =head1 NAME DBD::Gofer::Policy::rush - The 'rush' policy for DBD::Gofer =head1 SYNOPSIS $dbh = DBI->connect("dbi:Gofer:transport=...;policy=rush", ...) =head1 DESCRIPTION The C policy tries to make as few round-trips as possible. It's the opposite end of the policy spectrum to the C policy. Temporary docs: See the source code for list of policies and their defaults. In a future version the policies and their defaults will be defined in the pod and parsed out at load-time. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =cut PK1]\ ::Gofer/Policy/classic.pmnu[package DBD::Gofer::Policy::classic; # $Id: classic.pm 10087 2007-10-16 12:42:37Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; our $VERSION = "0.010088"; use base qw(DBD::Gofer::Policy::Base); __PACKAGE__->create_policy_subs({ # always use connect_cached on server connect_method => 'connect_cached', # use same methods on server as is called on client prepare_method => '', # don't skip the connect check since that also sets dbh attributes # although this makes connect more expensive, that's partly offset # by skip_ping=>1 below, which makes connect_cached very fast. skip_connect_check => 0, # most code doesn't rely on sth attributes being set after prepare skip_prepare_check => 1, # we're happy to use local method if that's the same as the remote skip_default_methods => 1, # ping is not important for DBD::Gofer and most transports skip_ping => 1, # only update dbh attributes on first contact with server dbh_attribute_update => 'first', # we'd like to set locally_* but can't because drivers differ # get_info results usually don't change cache_get_info => 1, }); 1; =head1 NAME DBD::Gofer::Policy::classic - The 'classic' policy for DBD::Gofer =head1 SYNOPSIS $dbh = DBI->connect("dbi:Gofer:transport=...;policy=classic", ...) The C policy is the default DBD::Gofer policy, so need not be included in the DSN. =head1 DESCRIPTION Temporary docs: See the source code for list of policies and their defaults. In a future version the policies and their defaults will be defined in the pod and parsed out at load-time. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =cut PK1]cGofer/Policy/Base.pmnu[package DBD::Gofer::Policy::Base; # $Id: Base.pm 10087 2007-10-16 12:42:37Z Tim $ # # Copyright (c) 2007, Tim Bunce, Ireland # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. use strict; use warnings; use Carp; our $VERSION = "0.010088"; our $AUTOLOAD; my %policy_defaults = ( # force connect method (unless overridden by go_connect_method=>'...' attribute) # if false: call same method on client as on server connect_method => 'connect', # force prepare method (unless overridden by go_prepare_method=>'...' attribute) # if false: call same method on client as on server prepare_method => 'prepare', skip_connect_check => 0, skip_default_methods => 0, skip_prepare_check => 0, skip_ping => 0, dbh_attribute_update => 'every', dbh_attribute_list => ['*'], locally_quote => 0, locally_quote_identifier => 0, cache_parse_trace_flags => 1, cache_parse_trace_flag => 1, cache_data_sources => 1, cache_type_info_all => 1, cache_tables => 0, cache_table_info => 0, cache_column_info => 0, cache_primary_key_info => 0, cache_foreign_key_info => 0, cache_statistics_info => 0, cache_get_info => 0, cache_func => 0, ); my $base_policy_file = $INC{"DBD/Gofer/Policy/Base.pm"}; __PACKAGE__->create_policy_subs(\%policy_defaults); sub create_policy_subs { my ($class, $policy_defaults) = @_; while ( my ($policy_name, $policy_default) = each %$policy_defaults) { my $policy_attr_name = "go_$policy_name"; my $sub = sub { # $policy->foo($attr, ...) #carp "$policy_name($_[1],...)"; # return the policy default value unless an attribute overrides it return (ref $_[1] && exists $_[1]->{$policy_attr_name}) ? $_[1]->{$policy_attr_name} : $policy_default; }; no strict 'refs'; *{$class . '::' . $policy_name} = $sub; } } sub AUTOLOAD { carp "Unknown policy name $AUTOLOAD used"; # only warn once no strict 'refs'; *$AUTOLOAD = sub { undef }; return undef; } sub new { my ($class, $args) = @_; my $policy = {}; bless $policy, $class; } sub DESTROY { }; 1; =head1 NAME DBD::Gofer::Policy::Base - Base class for DBD::Gofer policies =head1 SYNOPSIS $dbh = DBI->connect("dbi:Gofer:transport=...;policy=...", ...) =head1 DESCRIPTION DBD::Gofer can be configured via a 'policy' mechanism that allows you to fine-tune the number of round-trips to the Gofer server. The policies are grouped into classes (which may be subclassed) and referenced by the name of the class. The L class is the base class for all the policy classes and describes all the individual policy items. The Base policy is not used directly. You should use a policy class derived from it. =head1 POLICY CLASSES Three policy classes are supplied with DBD::Gofer: L is most 'transparent' but slowest because it makes more round-trips to the Gofer server. L is a reasonable compromise - it's the default policy. L is fastest, but may require code changes in your applications. Generally the default C policy is fine. When first testing an existing application with Gofer it is a good idea to start with the C policy first and then switch to C or a custom policy, for final testing. =head1 POLICY ITEMS These are temporary docs: See the source code for list of policies and their defaults. In a future version the policies and their defaults will be defined in the pod and parsed out at load-time. See the source code to this module for more details. =head1 POLICY CUSTOMIZATION XXX This area of DBD::Gofer is subject to change. There are three ways to customize policies: Policy classes are designed to influence the overall behaviour of DBD::Gofer with existing, unaltered programs, so they work in a reasonably optimal way without requiring code changes. You can implement new policy classes as subclasses of existing policies. In many cases individual policy items can be overridden on a case-by-case basis within your application code. You do this by passing a corresponding C<>> attribute into DBI methods by your application code. This let's you fine-tune the behaviour for special cases. The policy items are implemented as methods. In many cases the methods are passed parameters relating to the DBD::Gofer code being executed. This means the policy can implement dynamic behaviour that varies depending on the particular circumstances, such as the particular statement being executed. =head1 AUTHOR Tim Bunce, L =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Tim Bunce, Ireland. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =cut PK1]5vPvPFile/Developers.podnu[=head1 NAME DBD::File::Developers - Developers documentation for DBD::File =head1 SYNOPSIS package DBD::myDriver; use base qw( DBD::File ); sub driver { ... my $drh = $proto->SUPER::driver ($attr); ... return $drh->{class}; } sub CLONE { ... } package DBD::myDriver::dr; @ISA = qw( DBD::File::dr ); sub data_sources { ... } ... package DBD::myDriver::db; @ISA = qw( DBD::File::db ); sub init_valid_attributes { ... } sub init_default_attributes { ... } sub set_versions { ... } sub validate_STORE_attr { my ($dbh, $attrib, $value) = @_; ... } sub validate_FETCH_attr { my ($dbh, $attrib) = @_; ... } sub get_myd_versions { ... } package DBD::myDriver::st; @ISA = qw( DBD::File::st ); sub FETCH { ... } sub STORE { ... } package DBD::myDriver::Statement; @ISA = qw( DBD::File::Statement ); package DBD::myDriver::Table; @ISA = qw( DBD::File::Table ); my %reset_on_modify = ( myd_abc => "myd_foo", myd_mno => "myd_bar", ); __PACKAGE__->register_reset_on_modify (\%reset_on_modify); my %compat_map = ( abc => 'foo_abc', xyz => 'foo_xyz', ); __PACKAGE__->register_compat_map (\%compat_map); sub bootstrap_table_meta { ... } sub init_table_meta { ... } sub table_meta_attr_changed { ... } sub open_data { ... } sub fetch_row { ... } sub push_row { ... } sub push_names { ... } # optimize the SQL engine by add one or more of sub update_current_row { ... } # or sub update_specific_row { ... } # or sub update_one_row { ... } # or sub insert_new_row { ... } # or sub delete_current_row { ... } # or sub delete_one_row { ... } =head1 DESCRIPTION This document describes how DBD developers can write DBD::File based DBI drivers. It supplements L and L, which you should read first. =head1 CLASSES Each DBI driver must provide a package global C method and three DBI related classes: =over 4 =item DBD::File::dr Driver package, contains the methods DBI calls indirectly via DBI interface: DBI->connect ('DBI:DBM:', undef, undef, {}) # invokes package DBD::DBM::dr; @DBD::DBM::dr::ISA = qw( DBD::File::dr ); sub connect ($$;$$$) { ... } Similar for C<< data_sources >> and C<< disconnect_all >>. Pure Perl DBI drivers derived from DBD::File do not usually need to override any of the methods provided through the DBD::XXX::dr package however if you need additional initialization in the connect method you may need to. =item DBD::File::db Contains the methods which are called through DBI database handles (C<< $dbh >>). e.g., $sth = $dbh->prepare ("select * from foo"); # returns the f_encoding setting for table foo $dbh->csv_get_meta ("foo", "f_encoding"); DBD::File provides the typical methods required here. Developers who write DBI drivers based on DBD::File need to override the methods C<< set_versions >> and C<< init_valid_attributes >>. =item DBD::File::st Contains the methods to deal with prepared statement handles. e.g., $sth->execute () or die $sth->errstr; =back =head2 DBD::File This is the main package containing the routines to initialize DBD::File based DBI drivers. Primarily the C<< DBD::File::driver >> method is invoked, either directly from DBI when the driver is initialized or from the derived class. package DBD::DBM; use base qw( DBD::File ); sub driver { my ($class, $attr) = @_; ... my $drh = $class->SUPER::driver ($attr); ... return $drh; } It is not necessary to implement your own driver method as long as additional initialization (e.g. installing more private driver methods) is not required. You do not need to call C<< setup_driver >> as DBD::File takes care of it. =head2 DBD::File::dr The driver package contains the methods DBI calls indirectly via the DBI interface (see L). DBD::File based DBI drivers usually do not need to implement anything here, it is enough to do the basic initialization: package DBD:XXX::dr; @DBD::XXX::dr::ISA = qw (DBD::File::dr); $DBD::XXX::dr::imp_data_size = 0; $DBD::XXX::dr::data_sources_attr = undef; $DBD::XXX::ATTRIBUTION = "DBD::XXX $DBD::XXX::VERSION by Hans Mustermann"; =head2 DBD::File::db This package defines the database methods, which are called via the DBI database handle C<< $dbh >>. Methods provided by DBD::File: =over 4 =item ping Simply returns the content of the C<< Active >> attribute. Override when your driver needs more complicated actions here. =item prepare Prepares a new SQL statement to execute. Returns a statement handle, C<< $sth >> - instance of the DBD:XXX::st. It is neither required nor recommended to override this method. =item FETCH Fetches an attribute of a DBI database object. Private handle attributes must have a prefix (this is mandatory). If a requested attribute is detected as a private attribute without a valid prefix, the driver prefix (written as C<$drv_prefix>) is added. The driver prefix is extracted from the attribute name and verified against C<< $dbh->{$drv_prefix . "valid_attrs"} >> (when it exists). If the requested attribute value is not listed as a valid attribute, this method croaks. If the attribute is valid and readonly (listed in C<< $dbh->{ $drv_prefix . "readonly_attrs" } >> when it exists), a real copy of the attribute value is returned. So it's not possible to modify C from outside of DBD::File::db or a derived class. =item STORE Stores a database private attribute. Private handle attributes must have a prefix (this is mandatory). If a requested attribute is detected as a private attribute without a valid prefix, the driver prefix (written as C<$drv_prefix>) is added. If the database handle has an attribute C<${drv_prefix}_valid_attrs> - for attribute names which are not listed in that hash, this method croaks. If the database handle has an attribute C<${drv_prefix}_readonly_attrs>, only attributes which are not listed there can be stored (once they are initialized). Trying to overwrite such an immutable attribute forces this method to croak. An example of a valid attributes list can be found in C<< DBD::File::db::init_valid_attributes >>. =item set_versions This method sets the attribute C with the version of DBD::File. This method is called at the begin of the C phase. When overriding this method, do not forget to invoke the superior one. =item init_valid_attributes This method is called after the database handle is instantiated as the first attribute initialization. C<< DBD::File::db::init_valid_attributes >> initializes the attributes C and C. When overriding this method, do not forget to invoke the superior one, preferably before doing anything else. Compatibility table attribute access must be initialized here to allow DBD::File to instantiate the map tie: # for DBD::CSV $dbh->{csv_meta} = "csv_tables"; # for DBD::DBM $dbh->{dbm_meta} = "dbm_tables"; # for DBD::AnyData $dbh->{ad_meta} = "ad_tables"; =item init_default_attributes This method is called after the database handle is instantiated to initialize the default attributes. C<< DBD::File::db::init_default_attributes >> initializes the attributes C, C, C, C. When the derived implementor class provides the attribute to validate attributes (e.g. C<< $dbh->{dbm_valid_attrs} = {...}; >>) or the attribute containing the immutable attributes (e.g. C<< $dbh->{dbm_readonly_attrs} = {...}; >>), the attributes C, C, C and C are added (when available) to the list of valid and immutable attributes (where C is interpreted as the driver prefix). If C is set, an attribute with the name in C is initialized providing restricted read/write access to the meta data of the tables using C in the first (table) level and C for the meta attribute level. C uses C to initialize the second level tied hash on FETCH/STORE. The C class uses C to FETCH attribute values and C to STORE attribute values. This allows it to map meta attributes for compatibility reasons. =item get_single_table_meta =item get_file_meta Retrieve an attribute from a table's meta information. The method signature is C<< get_file_meta ($dbh, $table, $attr) >>. This method is called by the injected db handle method C<< ${drv_prefix}get_meta >>. While get_file_meta allows C<$table> or C<$attr> to be a list of tables or attributes to retrieve, get_single_table_meta allows only one table name and only one attribute name. A table name of C<'.'> (single dot) is interpreted as the default table and this will retrieve the appropriate attribute globally from the dbh. This has the same restrictions as C<< $dbh->{$attrib} >>. get_file_meta allows C<'+'> and C<'*'> as wildcards for table names and C<$table> being a regular expression matching against the table names (evaluated without the default table). The table name C<'*'> is I. The table name C<'+'> is I (/^[_A-Za-z0-9]+$/). The table meta information is retrieved using the get_table_meta and get_table_meta_attr methods of the table class of the implementation. =item set_single_table_meta =item set_file_meta Sets an attribute in a table's meta information. The method signature is C<< set_file_meta ($dbh, $table, $attr, $value) >>. This method is called by the injected db handle method C<< ${drv_prefix}set_meta >>. While set_file_meta allows C<$table> to be a list of tables and C<$attr> to be a hash of several attributes to set, set_single_table_meta allows only one table name and only one attribute name/value pair. The wildcard characters for the table name are the same as for get_file_meta. The table meta information is updated using the get_table_meta and set_table_meta_attr methods of the table class of the implementation. =item clear_file_meta Clears all meta information cached about a table. The method signature is C<< clear_file_meta ($dbh, $table) >>. This method is called by the injected db handle method C<< ${drv_prefix}clear_meta >>. =back =head2 DBD::File::st Contains the methods to deal with prepared statement handles: =over 4 =item FETCH Fetches statement handle attributes. Supported attributes (for full overview see L) are C, C, C and C in case that SQL::Statement is used as SQL execution engine and a statement is successful prepared. When SQL::Statement has additional information about a table, those information are returned. Otherwise, the same defaults as in L are used. This method usually requires extending in a derived implementation. See L or L for some example. =back =head2 DBD::File::TableSource::FileSystem Provides data sources and table information on database driver and database handle level. package DBD::File::TableSource::FileSystem; sub data_sources ($;$) { my ($class, $drh, $attrs) = @_; ... } sub avail_tables { my ($class, $drh) = @_; ... } The C method is called when the user invokes any of the following: @ary = DBI->data_sources ($driver); @ary = DBI->data_sources ($driver, \%attr); @ary = $dbh->data_sources (); @ary = $dbh->data_sources (\%attr); The C method is called when the user invokes any of the following: @names = $dbh->tables ($catalog, $schema, $table, $type); $sth = $dbh->table_info ($catalog, $schema, $table, $type); $sth = $dbh->table_info ($catalog, $schema, $table, $type, \%attr); $dbh->func ("list_tables"); Every time where an C<\%attr> argument can be specified, this C<\%attr> object's C attribute is preferred over the C<$dbh> attribute or the driver default. =head2 DBD::File::DataSource::Stream package DBD::File::DataSource::Stream; @DBD::File::DataSource::Stream::ISA = 'DBI::DBD::SqlEngine::DataSource'; sub complete_table_name { my ($self, $meta, $file, $respect_case) = @_; ... } Clears all meta attributes identifying a file: C, C and C. The table name is set according to C<$respect_case> and C<< $meta->{sql_identifier_case} >> (SQL_IC_LOWER, SQL_IC_UPPER). package DBD::File::DataSource::Stream; sub apply_encoding { my ($self, $meta, $fn) = @_; ... } Applies the encoding from I (C<< $meta->{f_encoding} >>) to the file handled opened in C. package DBD::File::DataSource::Stream; sub open_data { my ($self, $meta, $attrs, $flags) = @_; ... } Opens (C) the file handle provided in C<< $meta->{f_file} >>. package DBD::File::DataSource::Stream; sub can_flock { ... } Returns whether C is available or not (avoids retesting in subclasses). =head2 DBD::File::DataSource::File package DBD::File::DataSource::File; sub complete_table_name ($$;$) { my ($self, $meta, $table, $respect_case) = @_; ... } The method C tries to map a filename to the associated table name. It is called with a partially filled meta structure for the resulting table containing at least the following attributes: C<< f_ext >>, C<< f_dir >>, C<< f_lockfile >> and C<< sql_identifier_case >>. If a file/table map can be found then this method sets the C<< f_fqfn >>, C<< f_fqbn >>, C<< f_fqln >> and C<< table_name >> attributes in the meta structure. If a map cannot be found the table name will be undef. package DBD::File::DataSource::File; sub open_data ($) { my ($self, $meta, $attrs, $flags) = @_; ... } Depending on the attributes set in the table's meta data, the following steps are performed. Unless C<< f_dontopen >> is set to a true value, C<< f_fqfn >> must contain the full qualified file name for the table to work on (file2table ensures this). The encoding in C<< f_encoding >> is applied if set and the file is opened. If C<> (full qualified lock name) is set, this file is opened, too. Depending on the value in C<< f_lock >>, the appropriate lock is set on the opened data file or lock file. =head2 DBD::File::Statement Derives from DBI::SQL::Nano::Statement to provide following method: =over 4 =item open_table Implements the open_table method required by L and L. All the work for opening the file(s) belonging to the table is handled and parametrized in DBD::File::Table. Unless you intend to add anything to the following implementation, an empty DBD::XXX::Statement package satisfies DBD::File. sub open_table ($$$$$) { my ($self, $data, $table, $createMode, $lockMode) = @_; my $class = ref $self; $class =~ s/::Statement/::Table/; my $flags = { createMode => $createMode, lockMode => $lockMode, }; $self->{command} eq "DROP" and $flags->{dropMode} = 1; return $class->new ($data, { table => $table }, $flags); } # open_table =back =head2 DBD::File::Table Derives from DBI::SQL::Nano::Table and provides physical file access for the table data which are stored in the files. =over 4 =item bootstrap_table_meta Initializes a table meta structure. Can be safely overridden in a derived class, as long as the C<< SUPER >> method is called at the end of the overridden method. It copies the following attributes from the database into the table meta data C<< f_dir >>, C<< f_ext >>, C<< f_encoding >>, C<< f_lock >>, C<< f_schema >> and C<< f_lockfile >> and makes them sticky to the table. This method should be called before you attempt to map between file name and table name to ensure the correct directory, extension etc. are used. =item init_table_meta Initializes more attributes of the table meta data - usually more expensive ones (e.g. those which require class instantiations) - when the file name and the table name could mapped. =item get_table_meta Returns the table meta data. If there are none for the required table, a new one is initialized. When it fails, nothing is returned. On success, the name of the table and the meta data structure is returned. =item get_table_meta_attr Returns a single attribute from the table meta data. If the attribute name appears in C<%compat_map>, the attribute name is updated from there. =item set_table_meta_attr Sets a single attribute in the table meta data. If the attribute name appears in C<%compat_map>, the attribute name is updated from there. =item table_meta_attr_changed Called when an attribute of the meta data is modified. If the modified attribute requires to reset a calculated attribute, the calculated attribute is reset (deleted from meta data structure) and the I flag is removed, too. The decision is made based on C<%register_reset_on_modify>. =item register_reset_on_modify Allows C to reset meta attributes when special attributes are modified. For DBD::File, modifying one of C, C, C or C will reset C. DBD::DBM extends the list for C and C to reset the value of C. If your DBD has calculated values in the meta data area, then call C: my %reset_on_modify = (xxx_foo => "xxx_bar"); __PACKAGE__->register_reset_on_modify (\%reset_on_modify); =item register_compat_map Allows C and C to update the attribute name to the current favored one: # from DBD::DBM my %compat_map = (dbm_ext => "f_ext"); __PACKAGE__->register_compat_map (\%compat_map); =item open_file Called to open the table's data file. Depending on the attributes set in the table's meta data, the following steps are performed. Unless C<< f_dontopen >> is set to a true value, C<< f_fqfn >> must contain the full qualified file name for the table to work on (file2table ensures this). The encoding in C<< f_encoding >> is applied if set and the file is opened. If C<> (full qualified lock name) is set, this file is opened, too. Depending on the value in C<< f_lock >>, the appropriate lock is set on the opened data file or lock file. After this is done, a derived class might add more steps in an overridden C<< open_file >> method. =item new Instantiates the table. This is done in 3 steps: 1. get the table meta data 2. open the data file 3. bless the table data structure using inherited constructor new It is not recommended to override the constructor of the table class. Find a reasonable place to add you extensions in one of the above four methods. =item drop Implements the abstract table method for the C<< DROP >> command. Discards table meta data after all files belonging to the table are closed and unlinked. Overriding this method might be reasonable in very rare cases. =item seek Implements the abstract table method used when accessing the table from the engine. C<< seek >> is called every time the engine uses dumb algorithms for iterating over the table content. =item truncate Implements the abstract table method used when dumb table algorithms for C<< UPDATE >> or C<< DELETE >> need to truncate the table storage after the last written row. =back You should consult the documentation of C<< SQL::Eval::Table >> (see L) to get more information about the abstract methods of the table's base class you have to override and a description of the table meta information expected by the SQL engines. =head1 AUTHOR The module DBD::File is currently maintained by H.Merijn Brand < h.m.brand at xs4all.nl > and Jens Rehsack < rehsack at googlemail.com > The original author is Jochen Wiedmann. =head1 COPYRIGHT AND LICENSE Copyright (C) 2010-2013 by H.Merijn Brand & Jens Rehsack All rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =cut PK1],0H;;File/Roadmap.podnu[=head1 NAME DBD::File::Roadmap - Planned Enhancements for DBD::File and pure Perl DBD's Jens Rehsack - May 2010 =head1 SYNOPSIS This document gives a high level overview of the future of the DBD::File DBI driver and groundwork for pure Perl DBI drivers. The planned enhancements cover features, testing, performance, reliability, extensibility and more. =head1 CHANGES AND ENHANCEMENTS =head2 Features There are some features missing we would like to add, but there is no time plan: =over 4 =item LOCK TABLE The newly implemented internal common table meta storage area would allow us to implement LOCK TABLE support based on file system C support. =item Transaction support While DBD::AnyData recommends explicitly committing by importing and exporting tables, DBD::File might be enhanced in a future version to allow transparent transactions using the temporary tables of SQL::Statement as shadow (dirty) tables. Transaction support will heavily rely on lock table support. =item Data Dictionary Persistence SQL::Statement provides dictionary information when a "CREATE TABLE ..." statement is executed. This dictionary is preserved for some statement handle attribute fetches (as C or C). It is planned to extend DBD::File to support data dictionaries to work on the tables in it. It is not planned to support one table in different dictionaries, but you can have several dictionaries in one directory. =item SQL Engine selecting on connect Currently the SQL engine selected is chosen during the loading of the module L. Ideally end users should be able to select the engine used in C<< DBI->connect () >> with a special DBD::File attribute. =back Other points of view to the planned features (and more features for the SQL::Statement engine) are shown in L. =head2 Testing DBD::File and the dependent DBD::DBM requires a lot more automated tests covering API stability and compatibility with optional modules like SQL::Statement. =head2 Performance Several arguments for support of features like indexes on columns and cursors are made for DBD::CSV (which is a DBD::File based driver, too). Similar arguments could be made for DBD::DBM, DBD::AnyData, DBD::RAM or DBD::PO etc. To improve the performance of the underlying SQL engines, a clean re-implementation seems to be required. Currently both engines are prematurely optimized and therefore it is not trivial to provide further optimization without the risk of breaking existing features. Join the DBI developers IRC channel at L to participate or post to the DBI Developers Mailing List. =head2 Reliability DBD::File currently lacks the following points: =over 4 =item duplicate table names It is currently possible to access a table quoted with a relative path (a) and additionally using an absolute path (b). If (a) and (b) are the same file that is not recognized (except for flock protection handled by the Operating System) and two independent tables are handled. =item invalid table names The current implementation does not prevent someone choosing a directory name as a physical file name for the table to open. =back =head2 Extensibility I (Jens Rehsack) have some (partially for example only) DBD's in mind: =over 4 =item DBD::Sys Derive DBD::Sys from a common code base shared with DBD::File which handles all the emulation DBI needs (as getinfo, SQL engine handling, ...) =item DBD::Dir Provide a DBD::File derived to work with fixed table definitions through the file system to demonstrate how DBI / Pure Perl DBDs could handle databases with hierarchical structures. =item DBD::Join Provide a DBI driver which is able to manage multiple connections to other Databases (as DBD::Multiplex), but allow them to point to different data sources and allow joins between the tables of them: # Example # Let table 'lsof' being a table in DBD::Sys giving a list of open files using lsof utility # Let table 'dir' being a atable from DBD::Dir $sth = $dbh->prepare( "select * from dir,lsof where path='/documents' and dir.entry = lsof.filename" ) $sth->execute(); # gives all open files in '/documents' ... # Let table 'filesys' a DBD::Sys table of known file systems on current host # Let table 'applications' a table of your Configuration Management Database # where current applications (relocatable, with mountpoints for filesystems) # are stored $sth = dbh->prepare( "select * from applications,filesys where " . "application.mountpoint = filesys.mountpoint and ". "filesys.mounted is true" ); $sth->execute(); # gives all currently mounted applications on this host =back =head1 PRIORITIES Our priorities are focused on current issues. Initially many new test cases for DBD::File and DBD::DBM should be added to the DBI test suite. After that some additional documentation on how to use the DBD::File API will be provided. Any additional priorities will come later and can be modified by (paying) users. =head1 RESOURCES AND CONTRIBUTIONS See L for I. If your company has benefited from DBI, please consider if it could make a donation to The Perl Foundation "DBI Development" fund at L to secure future development. Alternatively, if your company would benefit from a specific new DBI feature, please consider sponsoring it's development through the options listed in the section "Commercial Support from the Author" on L. Using such targeted financing allows you to contribute to DBI development and rapidly get something specific and directly valuable to you in return. My company also offers annual support contracts for the DBI, which provide another way to support the DBI and get something specific in return. Contact me for details. Thank you. =cut PK1]ɻKFile/HowTo.podnu[=head1 NAME DBD::File::HowTo - Guide to create DBD::File based driver =head1 SYNOPSIS perldoc DBD::File::HowTo perldoc DBI perldoc DBI::DBD perldoc DBD::File::Developers perldoc DBI::DBD::SqlEngine::Developers perldoc DBI::DBD::SqlEngine perldoc SQL::Eval perldoc DBI::DBD::SqlEngine::HowTo perldoc SQL::Statement::Embed perldoc DBD::File perldoc DBD::File::HowTo perldoc DBD::File::Developers =head1 DESCRIPTION This document provides a step-by-step guide, how to create a new C based DBD. It expects that you carefully read the L documentation and that you're familiar with L and had read and understood L. This document addresses experienced developers who are really sure that they need to invest time when writing a new DBI Driver. Writing a DBI Driver is neither a weekend project nor an easy job for hobby coders after work. Expect one or two man-month of time for the first start. Those who are still reading, should be able to sing the rules of L. Of course, DBD::File is a DBI::DBD::SqlEngine and you surely read L before continuing here. =head1 CREATING DRIVER CLASSES Do you have an entry in DBI's DBD registry? For this guide, a prefix of C is assumed. =head2 Sample Skeleton package DBD::Foo; use strict; use warnings; use vars qw(@ISA $VERSION); use base qw(DBD::File); use DBI (); $VERSION = "0.001"; package DBD::Foo::dr; use vars qw(@ISA $imp_data_size); @ISA = qw(DBD::File::dr); $imp_data_size = 0; package DBD::Foo::db; use vars qw(@ISA $imp_data_size); @ISA = qw(DBD::File::db); $imp_data_size = 0; package DBD::Foo::st; use vars qw(@ISA $imp_data_size); @ISA = qw(DBD::File::st); $imp_data_size = 0; package DBD::Foo::Statement; use vars qw(@ISA); @ISA = qw(DBD::File::Statement); package DBD::Foo::Table; use vars qw(@ISA); @ISA = qw(DBD::File::Table); 1; Tiny, eh? And all you have now is a DBD named foo which will is able to deal with temporary tables, as long as you use L. In L environments, this DBD can do nothing. =head2 Start over Based on L, we're now having a driver which could do basic things. Of course, it should now derive from DBD::File instead of DBI::DBD::SqlEngine, shouldn't it? DBD::File extends DBI::DBD::SqlEngine to deal with any kind of files. In principle, the only extensions required are to the table class: package DBD::Foo::Table; sub bootstrap_table_meta { my ( $self, $dbh, $meta, $table ) = @_; # initialize all $meta attributes which might be relevant for # file2table return $self->SUPER::bootstrap_table_meta($dbh, $meta, $table); } sub init_table_meta { my ( $self, $dbh, $meta, $table ) = @_; # called after $meta contains the results from file2table # initialize all missing $meta attributes $self->SUPER::init_table_meta( $dbh, $meta, $table ); } In case C doesn't open the files as the driver needs that, override it! sub open_file { my ( $self, $meta, $attrs, $flags ) = @_; # ensure that $meta->{f_dontopen} is set $self->SUPER::open_file( $meta, $attrs, $flags ); # now do what ever needs to be done } Combined with the methods implemented using the L guide, the table is full working and you could try a start over. =head2 User comfort C since C<0.39> consolidates all persistent meta data of a table into a single structure stored in C<< $dbh->{f_meta} >>. With C version C<0.41> and C version C<0.05>, this consolidation moves to L. It's still the C<< $dbh->{$drv_prefix . "_meta"} >> attribute which cares, so what you learned at this place before, is still valid. sub init_valid_attributes { my $dbh = $_[0]; $dbh->SUPER::init_valid_attributes (); $dbh->{foo_valid_attrs} = { ... }; $dbh->{foo_readonly_attrs} = { ... }; $dbh->{foo_meta} = "foo_tables"; return $dbh; } See updates at L. =head2 Testing Now you should have your own DBD::File based driver. Was easy, wasn't it? But does it work well? Prove it by writing tests and remember to use dbd_edit_mm_attribs from L to ensure testing even rare cases. =head1 AUTHOR This guide is written by Jens Rehsack. DBD::File is written by Jochen Wiedmann and Jeff Zucker. The module DBD::File is currently maintained by H.Merijn Brand < h.m.brand at xs4all.nl > and Jens Rehsack < rehsack at googlemail.com > =head1 COPYRIGHT AND LICENSE Copyright (C) 2010 by H.Merijn Brand & Jens Rehsack All rights reserved. You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file. =cut PK1]e!}0}0 ExampleP.pmnu[{ package DBD::ExampleP; use strict; use Symbol; use DBI qw(:sql_types); require File::Spec; our (@EXPORT,$VERSION,@statnames,%statnames,@stattypes,%stattypes, @statprec,%statprec,$drh,); @EXPORT = qw(); # Do NOT @EXPORT anything. $VERSION = "12.014311"; # $Id: ExampleP.pm 14310 2010-08-02 06:35:25Z Jens $ # # Copyright (c) 1994,1997,1998 Tim Bunce # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. @statnames = qw(dev ino mode nlink uid gid rdev size atime mtime ctime blksize blocks name); @statnames{@statnames} = (0 .. @statnames-1); @stattypes = (SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_INTEGER, SQL_VARCHAR); @stattypes{@statnames} = @stattypes; @statprec = ((10) x (@statnames-1), 1024); @statprec{@statnames} = @statprec; die unless @statnames == @stattypes; die unless @statprec == @stattypes; $drh = undef; # holds driver handle once initialised #$gensym = "SYM000"; # used by st::execute() for filehandles sub driver{ return $drh if $drh; my($class, $attr) = @_; $class .= "::dr"; ($drh) = DBI::_new_drh($class, { 'Name' => 'ExampleP', 'Version' => $VERSION, 'Attribution' => 'DBD Example Perl stub by Tim Bunce', }, ['example implementors private data '.__PACKAGE__]); $drh; } sub CLONE { undef $drh; } } { package DBD::ExampleP::dr; # ====== DRIVER ====== $imp_data_size = 0; use strict; sub connect { # normally overridden, but a handy default my($drh, $dbname, $user, $auth)= @_; my ($outer, $dbh) = DBI::_new_dbh($drh, { Name => $dbname, examplep_private_dbh_attrib => 42, # an example, for testing }); $dbh->{examplep_get_info} = { 29 => '"', # SQL_IDENTIFIER_QUOTE_CHAR 41 => '.', # SQL_CATALOG_NAME_SEPARATOR 114 => 1, # SQL_CATALOG_LOCATION }; #$dbh->{Name} = $dbname; $dbh->STORE('Active', 1); return $outer; } sub data_sources { return ("dbi:ExampleP:dir=."); # possibly usefully meaningless } } { package DBD::ExampleP::db; # ====== DATABASE ====== $imp_data_size = 0; use strict; sub prepare { my($dbh, $statement)= @_; my @fields; my($fields, $dir) = $statement =~ m/^\s*select\s+(.*?)\s+from\s+(\S*)/i; if (defined $fields and defined $dir) { @fields = ($fields eq '*') ? keys %DBD::ExampleP::statnames : split(/\s*,\s*/, $fields); } else { return $dbh->set_err($DBI::stderr, "Syntax error in select statement (\"$statement\")") unless $statement =~ m/^\s*set\s+/; # the SET syntax is just a hack so the ExampleP driver can # be used to test non-select statements. # Now we have DBI::DBM etc., ExampleP should be deprecated } my ($outer, $sth) = DBI::_new_sth($dbh, { 'Statement' => $statement, examplep_private_sth_attrib => 24, # an example, for testing }, ['example implementors private data '.__PACKAGE__]); my @bad = map { defined $DBD::ExampleP::statnames{$_} ? () : $_ } @fields; return $dbh->set_err($DBI::stderr, "Unknown field names: @bad") if @bad; $outer->STORE('NUM_OF_FIELDS' => scalar(@fields)); $sth->{examplep_ex_dir} = $dir if defined($dir) && $dir !~ /\?/; $outer->STORE('NUM_OF_PARAMS' => ($dir) ? $dir =~ tr/?/?/ : 0); if (@fields) { $outer->STORE('NAME' => \@fields); $outer->STORE('NULLABLE' => [ (0) x @fields ]); $outer->STORE('SCALE' => [ (0) x @fields ]); } $outer; } sub table_info { my $dbh = shift; my ($catalog, $schema, $table, $type) = @_; my @types = split(/["']*,["']/, $type || 'TABLE'); my %types = map { $_=>$_ } @types; # Return a list of all subdirectories my $dh = Symbol::gensym(); # "DBD::ExampleP::".++$DBD::ExampleP::gensym; my $dir = $catalog || File::Spec->curdir(); my @list; if ($types{VIEW}) { # for use by test harness push @list, [ undef, "schema", "table", 'VIEW', undef ]; push @list, [ undef, "sch-ema", "table", 'VIEW', undef ]; push @list, [ undef, "schema", "ta-ble", 'VIEW', undef ]; push @list, [ undef, "sch ema", "table", 'VIEW', undef ]; push @list, [ undef, "schema", "ta ble", 'VIEW', undef ]; } if ($types{TABLE}) { no strict 'refs'; opendir($dh, $dir) or return $dbh->set_err(int($!), "Failed to open directory $dir: $!"); while (defined(my $item = readdir($dh))) { if ($^O eq 'VMS') { # if on VMS then avoid warnings from catdir if you use a file # (not a dir) as the item below next if $item !~ /\.dir$/oi; } my $file = File::Spec->catdir($dir,$item); next unless -d $file; my($dev, $ino, $mode, $nlink, $uid) = lstat($file); my $pwnam = undef; # eval { scalar(getpwnam($uid)) } || $uid; push @list, [ $dir, $pwnam, $item, 'TABLE', undef ]; } close($dh); } # We would like to simply do a DBI->connect() here. However, # this is wrong if we are in a subclass like DBI::ProxyServer. $dbh->{'dbd_sponge_dbh'} ||= DBI->connect("DBI:Sponge:", '','') or return $dbh->set_err($DBI::err, "Failed to connect to DBI::Sponge: $DBI::errstr"); my $attr = { 'rows' => \@list, 'NUM_OF_FIELDS' => 5, 'NAME' => ['TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS'], 'TYPE' => [DBI::SQL_VARCHAR(), DBI::SQL_VARCHAR(), DBI::SQL_VARCHAR(), DBI::SQL_VARCHAR(), DBI::SQL_VARCHAR() ], 'NULLABLE' => [1, 1, 1, 1, 1] }; my $sdbh = $dbh->{'dbd_sponge_dbh'}; my $sth = $sdbh->prepare("SHOW TABLES FROM $dir", $attr) or return $dbh->set_err($sdbh->err(), $sdbh->errstr()); $sth; } sub type_info_all { my ($dbh) = @_; my $ti = [ { 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, }, [ 'VARCHAR', DBI::SQL_VARCHAR, 1024, "'","'", undef, 0, 1, 1, 0, 0,0,undef,0,0 ], [ 'INTEGER', DBI::SQL_INTEGER, 10, "","", undef, 0, 0, 1, 0, 0,0,undef,0,0 ], ]; return $ti; } sub ping { (shift->FETCH('Active')) ? 2 : 0; # the value 2 is checked for by t/80proxy.t } sub disconnect { shift->STORE(Active => 0); return 1; } sub get_info { my ($dbh, $info_type) = @_; return $dbh->{examplep_get_info}->{$info_type}; } sub FETCH { my ($dbh, $attrib) = @_; # In reality this would interrogate the database engine to # either return dynamic values that cannot be precomputed # or fetch and cache attribute values too expensive to prefetch. # else pass up to DBI to handle return $INC{"DBD/ExampleP.pm"} if $attrib eq 'example_driver_path'; return $dbh->SUPER::FETCH($attrib); } sub STORE { my ($dbh, $attrib, $value) = @_; # store only known attributes else pass up to DBI to handle if ($attrib eq 'examplep_set_err') { # a fake attribute to enable a test case where STORE issues a warning $dbh->set_err($value, $value); return; } if ($attrib eq 'AutoCommit') { # convert AutoCommit values to magic ones to let DBI # know that the driver has 'handled' the AutoCommit attribute $value = ($value) ? -901 : -900; } return $dbh->{$attrib} = $value if $attrib =~ /^examplep_/; return $dbh->SUPER::STORE($attrib, $value); } sub DESTROY { my $dbh = shift; $dbh->disconnect if $dbh->FETCH('Active'); undef } # This is an example to demonstrate the use of driver-specific # methods via $dbh->func(). # Use it as follows: # my @tables = $dbh->func($re, 'examplep_tables'); # # Returns all the tables that match the regular expression $re. sub examplep_tables { my $dbh = shift; my $re = shift; grep { $_ =~ /$re/ } $dbh->tables(); } sub parse_trace_flag { my ($h, $name) = @_; return 0x01000000 if $name eq 'foo'; return 0x02000000 if $name eq 'bar'; return 0x04000000 if $name eq 'baz'; return 0x08000000 if $name eq 'boo'; return 0x10000000 if $name eq 'bop'; return $h->SUPER::parse_trace_flag($name); } sub private_attribute_info { return { example_driver_path => undef }; } } { package DBD::ExampleP::st; # ====== STATEMENT ====== $imp_data_size = 0; use strict; no strict 'refs'; # cause problems with filehandles sub bind_param { my($sth, $param, $value, $attribs) = @_; $sth->{'dbd_param'}->[$param-1] = $value; return 1; } sub execute { my($sth, @dir) = @_; my $dir; if (@dir) { $sth->bind_param($_, $dir[$_-1]) or return foreach (1..@dir); } my $dbd_param = $sth->{'dbd_param'} || []; return $sth->set_err(2, @$dbd_param." values bound when $sth->{NUM_OF_PARAMS} expected") unless @$dbd_param == $sth->{NUM_OF_PARAMS}; return 0 unless $sth->{NUM_OF_FIELDS}; # not a select $dir = $dbd_param->[0] || $sth->{examplep_ex_dir}; return $sth->set_err(2, "No bind parameter supplied") unless defined $dir; $sth->finish; # # If the users asks for directory "long_list_4532", then we fake a # directory with files "file4351", "file4350", ..., "file0". # This is a special case used for testing, especially DBD::Proxy. # if ($dir =~ /^long_list_(\d+)$/) { $sth->{dbd_dir} = [ $1 ]; # array ref indicates special mode $sth->{dbd_datahandle} = undef; } else { $sth->{dbd_dir} = $dir; my $sym = Symbol::gensym(); # "DBD::ExampleP::".++$DBD::ExampleP::gensym; opendir($sym, $dir) or return $sth->set_err(2, "opendir($dir): $!"); $sth->{dbd_datahandle} = $sym; } $sth->STORE(Active => 1); return 1; } sub fetch { my $sth = shift; my $dir = $sth->{dbd_dir}; my %s; if (ref $dir) { # special fake-data test mode my $num = $dir->[0]--; unless ($num > 0) { $sth->finish(); return; } my $time = time; @s{@DBD::ExampleP::statnames} = ( 2051, 1000+$num, 0644, 2, $>, $), 0, 1024, $time, $time, $time, 512, 2, "file$num") } else { # normal mode my $dh = $sth->{dbd_datahandle} or return $sth->set_err($DBI::stderr, "fetch without successful execute"); my $f = readdir($dh); unless ($f) { $sth->finish; return; } # untaint $f so that we can use this for DBI taint tests ($f) = ($f =~ m/^(.*)$/); my $file = File::Spec->catfile($dir, $f); # put in all the data fields @s{ @DBD::ExampleP::statnames } = (lstat($file), $f); } # return just what fields the query asks for my @new = @s{ @{$sth->{NAME}} }; return $sth->_set_fbav(\@new); } *fetchrow_arrayref = \&fetch; sub finish { my $sth = shift; closedir($sth->{dbd_datahandle}) if $sth->{dbd_datahandle}; $sth->{dbd_datahandle} = undef; $sth->{dbd_dir} = undef; $sth->SUPER::finish(); return 1; } sub FETCH { my ($sth, $attrib) = @_; # In reality this would interrogate the database engine to # either return dynamic values that cannot be precomputed # or fetch and cache attribute values too expensive to prefetch. if ($attrib eq 'TYPE'){ return [ @DBD::ExampleP::stattypes{ @{ $sth->FETCH(q{NAME_lc}) } } ]; } elsif ($attrib eq 'PRECISION'){ return [ @DBD::ExampleP::statprec{ @{ $sth->FETCH(q{NAME_lc}) } } ]; } elsif ($attrib eq 'ParamValues') { my $dbd_param = $sth->{dbd_param} || []; my %pv = map { $_ => $dbd_param->[$_-1] } 1..@$dbd_param; return \%pv; } # else pass up to DBI to handle return $sth->SUPER::FETCH($attrib); } sub STORE { my ($sth, $attrib, $value) = @_; # would normally validate and only store known attributes # else pass up to DBI to handle return $sth->{$attrib} = $value if $attrib eq 'NAME' or $attrib eq 'NULLABLE' or $attrib eq 'SCALE' or $attrib eq 'PRECISION'; return $sth->SUPER::STORE($attrib, $value); } *parse_trace_flag = \&DBD::ExampleP::db::parse_trace_flag; } 1; # vim: sw=4:ts=8 PKM&1]ma:: Metadata.pmnu[PKM&1]`yjj;SqlEngine/Developers.podnu[PKM&1]SK*K*SqlEngine/HowTo.podnu[PKM&1]QGG SqlEngine.pmnu[PK1])bS99#File.pmnu[PK1]! nSponge.pmnu[PK1]kDBM.pmnu[PK1]}0YGofer.pmnu[PK1]7LNullP.pmnu[PK1]"CM''g1Mem.pmnu[PK1] Dۃ*YGofer/Transport/pipeone.pmnu[PK1]+3 $ $uGofer/Transport/stream.pmnu[PK1]]Ïr `Gofer/Transport/null.pmnu[PK1]=o11yGofer/Transport/Base.pmnu[PK1]_Gofer/Policy/pedantic.pmnu[PK1]3<ȍ% % vGofer/Policy/rush.pmnu[PK1]\ ::Gofer/Policy/classic.pmnu[PK1]c`Gofer/Policy/Base.pmnu[PK1]5vPvPFile/Developers.podnu[PK1],0H;;>UFile/Roadmap.podnu[PK1]ɻKlFile/HowTo.podnu[PK1]e!}0}0 ExampleP.pmnu[PKC