DBI-1.651/0000755000031300001440000000000015225400755011366 5ustar00merijnusersDBI-1.651/lib/0000755000031300001440000000000015225400755012134 5ustar00merijnusersDBI-1.651/lib/DBD/0000755000031300001440000000000015225400755012525 5ustar00merijnusersDBI-1.651/lib/DBD/File/0000755000031300001440000000000015225400755013404 5ustar00merijnusersDBI-1.651/lib/DBD/File/Roadmap.pod0000644000031300001440000001345215222214034015466 0ustar00merijnusers=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 F 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 DBI-1.651/lib/DBD/File/HowTo.pod0000644000031300001440000001135615206260124015147 0ustar00merijnusers=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 base qw(DBD::File); use DBI (); our $VERSION = "0.001"; package DBD::Foo::dr; our @ISA = qw(DBD::File::dr); our $imp_data_size = 0; package DBD::Foo::db; our @ISA = qw(DBD::File::db); our $imp_data_size = 0; package DBD::Foo::st; our @ISA = qw(DBD::File::st); our $imp_data_size = 0; package DBD::Foo::Statement; our @ISA = qw(DBD::File::Statement); package DBD::Foo::Table; our @ISA = qw(DBD::File::Table); 1; Tiny, eh? And all you have now is a DBD named foo which will be 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 < hmbrand at cpan.org > and Jens Rehsack < rehsack at googlemail.com > =head1 COPYRIGHT AND LICENSE Copyright (C) 2010-2026 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 DBI-1.651/lib/DBD/File/Developers.pod0000644000031300001440000005013115225122612016211 0ustar00merijnusers=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 < hmbrand at cpan.org > and Jens Rehsack < rehsack at googlemail.com > The original author is Jochen Wiedmann. =head1 COPYRIGHT AND LICENSE Copyright (C) 2010-2026 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 DBI-1.651/lib/DBD/ExampleP.pm0000644000031300001440000003021714656646601014612 0ustar00merijnusers{ package DBD::ExampleP; use strict; use warnings; 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 DBI-1.651/lib/DBD/DBM.pm0000644000031300001440000014543715222442652013502 0ustar00merijnusers####################################################################### # # DBD::DBM - a DBI driver for DBM files # # Copyright (c) 2004 by Jeff Zucker < jzucker AT cpan.org > # 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. # # USERS - see the pod at the bottom of this file # # DBD AUTHORS - see the comments in the code # ####################################################################### require 5.008; use strict; use warnings; ################# package DBD::DBM; ################# use base qw( DBD::File ); our ($drh,$methods_already_installed); our $VERSION = '0.08'; our $ATTRIBUTION = 'DBD::DBM 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 DBD::File # $attr->{Attribution} = 'DBD::DBM by Jens Rehsack'; $drh = $class->SUPER::driver($attr); # install private methods # # this requires that dbm_ (or foo_) be a registered prefix # but you can write private methods before official registration # by hacking the $dbd_prefix_registry in a private copy of DBI.pm # unless ( $methods_already_installed++ ) { DBD::DBM::st->install_method('dbm_schema'); } return $drh; } sub CLONE { undef $drh; } ##################### package DBD::DBM::dr; ##################### our $imp_data_size = 0; our @ISA = qw(DBD::File::dr); # you could put some :dr private methods here # you may need to over-ride some DBD::File::dr methods here # but you can probably get away with just letting it do the work # in most cases ##################### package DBD::DBM::db; ##################### our $imp_data_size = 0; our @ISA = qw(DBD::File::db); use Carp qw/carp/; sub validate_STORE_attr { my ( $dbh, $attrib, $value ) = @_; if ( $attrib eq "dbm_ext" or $attrib eq "dbm_lockfile" ) { ( my $newattrib = $attrib ) =~ s/^dbm_/f_/g; carp "Attribute '$attrib' is depreciated, use '$newattrib' instead" if ($^W); $attrib = $newattrib; } return $dbh->SUPER::validate_STORE_attr( $attrib, $value ); } sub validate_FETCH_attr { my ( $dbh, $attrib ) = @_; if ( $attrib eq "dbm_ext" or $attrib eq "dbm_lockfile" ) { ( my $newattrib = $attrib ) =~ s/^dbm_/f_/g; carp "Attribute '$attrib' is depreciated, use '$newattrib' instead" if ($^W); $attrib = $newattrib; } return $dbh->SUPER::validate_FETCH_attr($attrib); } sub set_versions { my $this = $_[0]; $this->{dbm_version} = $DBD::DBM::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 dbm_ or foo_ # # see the STORE methods below for how to check these attrs # $dbh->{dbm_valid_attrs} = { dbm_type => 1, # the global DBM type e.g. SDBM_File dbm_mldbm => 1, # the global MLDBM serializer dbm_cols => 1, # the global column names dbm_version => 1, # verbose DBD::DBM version dbm_store_metadata => 1, # column names, etc. dbm_berkeley_flags => 1, # for BerkeleyDB dbm_valid_attrs => 1, # DBD::DBM::db valid attrs dbm_readonly_attrs => 1, # DBD::DBM::db r/o attrs dbm_meta => 1, # DBD::DBM public access for f_meta dbm_tables => 1, # DBD::DBM public access for f_meta }; $dbh->{dbm_readonly_attrs} = { dbm_version => 1, # verbose DBD::DBM version dbm_valid_attrs => 1, # DBD::DBM::db valid attrs dbm_readonly_attrs => 1, # DBD::DBM::db r/o attrs dbm_meta => 1, # DBD::DBM public access for f_meta }; $dbh->{dbm_meta} = "dbm_tables"; return $dbh->SUPER::init_valid_attributes(); } sub init_default_attributes { my ( $dbh, $phase ) = @_; $dbh->SUPER::init_default_attributes($phase); $dbh->{f_lockfile} = '.lck'; return $dbh; } sub get_dbm_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 ) ); my $dver; my $dtype = $meta->{dbm_type}; eval { $dver = $meta->{dbm_type}->VERSION(); # *) when we're still alive here, everything went ok - no need to check for $@ $dtype .= " ($dver)"; }; if ( $meta->{dbm_mldbm} ) { $dtype .= ' + MLDBM'; eval { $dver = MLDBM->VERSION(); $dtype .= " ($dver)"; # (*) }; eval { my $ser_class = "MLDBM::Serializer::" . $meta->{dbm_mldbm}; my $ser_mod = $ser_class; $ser_mod =~ s|::|/|g; $ser_mod .= ".pm"; require $ser_mod; $dver = $ser_class->VERSION(); $dtype .= ' + ' . $ser_class; # (*) $dver and $dtype .= " ($dver)"; # (*) }; } return sprintf( "%s using %s", $dbh->{dbm_version}, $dtype ); } # you may need to over-ride some DBD::File::db methods here # but you can probably get away with just letting it do the work # in most cases ##################### package DBD::DBM::st; ##################### our $imp_data_size = 0; our @ISA = qw(DBD::File::st); sub FETCH { my ( $sth, $attr ) = @_; if ( $attr eq "NULLABLE" ) { my @colnames = $sth->sql_get_colnames(); # XXX only BerkeleyDB fails having NULL values for non-MLDBM databases, # none accept it for key - but it requires more knowledge between # queries and tables storage to return fully correct information $attr eq "NULLABLE" and return [ map { 0 } @colnames ]; } return $sth->SUPER::FETCH($attr); } # FETCH sub dbm_schema { my ( $sth, $tname ) = @_; return $sth->set_err( $DBI::stderr, 'No table name supplied!' ) unless $tname; my $tbl_meta = $sth->{Database}->func( $tname, "f_schema", "get_sql_engine_meta" ) or return $sth->set_err( $sth->{Database}->err(), $sth->{Database}->errstr() ); return $tbl_meta->{$tname}->{f_schema}; } # you could put some :st private methods here # you may need to over-ride some DBD::File::st methods here # but you can probably get away with just letting it do the work # in most cases ############################ package DBD::DBM::Statement; ############################ our @ISA = qw(DBD::File::Statement); ######################## package DBD::DBM::Table; ######################## use Carp; use Fcntl; our @ISA = qw(DBD::File::Table); my $dirfext = $^O eq 'VMS' ? '.sdbm_dir' : '.dir'; my %reset_on_modify = ( dbm_type => "dbm_tietype", dbm_mldbm => "dbm_tietype", ); __PACKAGE__->register_reset_on_modify( \%reset_on_modify ); my %compat_map = ( ( map { $_ => "dbm_$_" } qw(type mldbm store_metadata) ), dbm_ext => 'f_ext', dbm_file => 'f_file', dbm_lockfile => ' f_lockfile', ); __PACKAGE__->register_compat_map( \%compat_map ); sub bootstrap_table_meta { my ( $self, $dbh, $meta, $table ) = @_; $meta->{dbm_type} ||= $dbh->{dbm_type} || 'SDBM_File'; $meta->{dbm_mldbm} ||= $dbh->{dbm_mldbm} if ( $dbh->{dbm_mldbm} ); $meta->{dbm_berkeley_flags} ||= $dbh->{dbm_berkeley_flags}; defined $meta->{f_ext} or $meta->{f_ext} = $dbh->{f_ext}; unless ( defined( $meta->{f_ext} ) ) { my $ext; if ( $meta->{dbm_type} eq 'SDBM_File' or $meta->{dbm_type} eq 'ODBM_File' ) { $ext = '.pag/r'; } elsif ( $meta->{dbm_type} eq 'NDBM_File' ) { # XXX NDBM_File on FreeBSD (and elsewhere?) may actually be Berkeley # behind the scenes and so create a single .db file. if ( $^O =~ /bsd/i or lc($^O) eq 'darwin' ) { $ext = '.db/r'; } elsif ( $^O eq 'SunOS' or $^O eq 'Solaris' or $^O eq 'AIX' ) { $ext = '.pag/r'; # here it's implemented like dbm - just a bit improved } # else wrapped GDBM } defined($ext) and $meta->{f_ext} = $ext; } $self->SUPER::bootstrap_table_meta( $dbh, $meta, $table ); } sub init_table_meta { my ( $self, $dbh, $meta, $table ) = @_; $meta->{f_dontopen} = 1; unless ( defined( $meta->{dbm_tietype} ) ) { my $tie_type = $meta->{dbm_type}; $INC{"$tie_type.pm"} or require "$tie_type.pm"; $tie_type eq 'BerkeleyDB' and $tie_type = 'BerkeleyDB::Hash'; if ( $meta->{dbm_mldbm} ) { $INC{"MLDBM.pm"} or require "MLDBM.pm"; $meta->{dbm_usedb} = $tie_type; $tie_type = 'MLDBM'; } $meta->{dbm_tietype} = $tie_type; } unless ( defined( $meta->{dbm_store_metadata} ) ) { my $store = $dbh->{dbm_store_metadata}; defined($store) or $store = 1; $meta->{dbm_store_metadata} = $store; } unless ( defined( $meta->{col_names} ) ) { defined( $dbh->{dbm_cols} ) and $meta->{col_names} = $dbh->{dbm_cols}; } $self->SUPER::init_table_meta( $dbh, $meta, $table ); } sub open_data { my ( $className, $meta, $attrs, $flags ) = @_; $className->SUPER::open_data( $meta, $attrs, $flags ); unless ( $flags->{dropMode} ) { # TIEING # # XXX allow users to pass in a pre-created tied object # my @tie_args; if ( $meta->{dbm_type} eq 'BerkeleyDB' ) { my $DB_CREATE = BerkeleyDB::DB_CREATE(); my $DB_RDONLY = BerkeleyDB::DB_RDONLY(); my %tie_flags; if ( my $f = $meta->{dbm_berkeley_flags} ) { defined( $f->{DB_CREATE} ) and $DB_CREATE = delete $f->{DB_CREATE}; defined( $f->{DB_RDONLY} ) and $DB_RDONLY = delete $f->{DB_RDONLY}; %tie_flags = %$f; } my $open_mode = $flags->{lockMode} || $flags->{createMode} ? $DB_CREATE : $DB_RDONLY; @tie_args = ( -Filename => $meta->{f_fqbn}, -Flags => $open_mode, %tie_flags ); } else { my $open_mode = O_RDONLY; $flags->{lockMode} and $open_mode = O_RDWR; $flags->{createMode} and $open_mode = O_RDWR | O_CREAT | O_TRUNC; @tie_args = ( $meta->{f_fqbn}, $open_mode, 0666 ); } if ( $meta->{dbm_mldbm} ) { $MLDBM::UseDB = $meta->{dbm_usedb}; $MLDBM::Serializer = $meta->{dbm_mldbm}; } $meta->{hash} = {}; my $tie_class = $meta->{dbm_tietype}; eval { tie %{ $meta->{hash} }, $tie_class, @tie_args }; $@ and croak "Cannot tie(\%h $tie_class @tie_args): $@"; -f $meta->{f_fqfn} or croak( "No such file: '" . $meta->{f_fqfn} . "'" ); } unless ( $flags->{createMode} ) { my ( $meta_data, $schema, $col_names ); if ( $meta->{dbm_store_metadata} ) { $meta_data = $col_names = $meta->{hash}->{"_metadata \0"}; if ( $meta_data and $meta_data =~ m~(.+)~is ) { $schema = $col_names = $1; $schema =~ s~.*(.+).*~$1~is; $col_names =~ s~.*(.+).*~$1~is; } } $col_names ||= $meta->{col_names} || [ 'k', 'v' ]; $col_names = [ split /,/, $col_names ] if ( ref $col_names ne 'ARRAY' ); if ( $meta->{dbm_store_metadata} and not $meta->{hash}->{"_metadata \0"} ) { $schema or $schema = ''; $meta->{hash}->{"_metadata \0"} = "" . "$schema" . "" . join( ",", @{$col_names} ) . "" . ""; } $meta->{schema} = $schema; $meta->{col_names} = $col_names; } } # you must define drop # it is called from execute of a SQL DROP statement # sub drop ($$) { my ( $self, $data ) = @_; my $meta = $self->{meta}; $meta->{hash} and untie %{ $meta->{hash} }; $self->SUPER::drop($data); # XXX extra_files -f $meta->{f_fqbn} . $dirfext and $meta->{f_ext} eq '.pag/r' and unlink( $meta->{f_fqbn} . $dirfext ); return 1; } # you must define fetch_row, it is called on all fetches; # it MUST return undef when no rows are left to fetch; # checking for $ary[0] is specific to hashes so you'll # probably need some other kind of check for nothing-left. # as Janis might say: "undef's just another word for # nothing left to fetch" :-) # sub fetch_row ($$) { my ( $self, $data ) = @_; my $meta = $self->{meta}; # fetch with %each # my @ary = each %{ $meta->{hash} }; $meta->{dbm_store_metadata} and $ary[0] and $ary[0] eq "_metadata \0" and @ary = each %{ $meta->{hash} }; my ( $key, $val ) = @ary; unless ($key) { delete $self->{row}; return; } my @row = ( ref($val) eq 'ARRAY' ) ? ( $key, @$val ) : ( $key, $val ); $self->{row} = @row ? \@row : undef; return wantarray ? @row : \@row; } # you must define push_row except insert_new_row and update_specific_row is defined # it is called on inserts and updates as primitive # sub insert_new_row ($$$) { my ( $self, $data, $row_aryref ) = @_; my $meta = $self->{meta}; my $ncols = scalar( @{ $meta->{col_names} } ); my $nitems = scalar( @{$row_aryref} ); $ncols == $nitems or croak "You tried to insert $nitems, but table is created with $ncols columns"; my $key = shift @$row_aryref; my $exists; eval { $exists = exists( $meta->{hash}->{$key} ); }; $exists and croak "Row with PK '$key' already exists"; $meta->{hash}->{$key} = $meta->{dbm_mldbm} ? $row_aryref : $row_aryref->[0]; return 1; } # this is where you grab the column names from a CREATE statement # if you don't need to do that, it must be defined but can be empty # sub push_names ($$$) { my ( $self, $data, $row_aryref ) = @_; my $meta = $self->{meta}; # some sanity checks ... my $ncols = scalar(@$row_aryref); $ncols < 2 and croak "At least 2 columns are required for DBD::DBM tables ..."; !$meta->{dbm_mldbm} and $ncols > 2 and croak "Without serializing with MLDBM only 2 columns are supported, you give $ncols"; $meta->{col_names} = $row_aryref; return unless $meta->{dbm_store_metadata}; my $stmt = $data->{sql_stmt}; my $col_names = join( ',', @{$row_aryref} ); my $schema = $data->{Database}->{Statement}; $schema =~ s/^[^\(]+\((.+)\)$/$1/s; $schema = $stmt->schema_str() if ( $stmt->can('schema_str') ); $meta->{hash}->{"_metadata \0"} = "" . "$schema" . "$col_names" . ""; } # fetch_one_row, delete_one_row, update_one_row # are optimized for hash-style lookup without looping; # if you don't need them, omit them, they're optional # but, in that case you may need to define # truncate() and seek(), see below # sub fetch_one_row ($$;$) { my ( $self, $key_only, $key ) = @_; my $meta = $self->{meta}; $key_only and return $meta->{col_names}->[0]; exists $meta->{hash}->{$key} or return; my $val = $meta->{hash}->{$key}; $val = ( ref($val) eq 'ARRAY' ) ? $val : [$val]; my $row = [ $key, @$val ]; return wantarray ? @{$row} : $row; } sub delete_one_row ($$$) { my ( $self, $data, $aryref ) = @_; my $meta = $self->{meta}; delete $meta->{hash}->{ $aryref->[0] }; } sub update_one_row ($$$) { my ( $self, $data, $aryref ) = @_; my $meta = $self->{meta}; my $key = shift @$aryref; defined $key or return; my $row = ( ref($aryref) eq 'ARRAY' ) ? $aryref : [$aryref]; $meta->{hash}->{$key} = $meta->{dbm_mldbm} ? $row : $row->[0]; } sub update_specific_row ($$$$) { my ( $self, $data, $aryref, $origary ) = @_; my $meta = $self->{meta}; my $key = shift @$origary; my $newkey = shift @$aryref; return unless ( defined $key ); $key eq $newkey or delete $meta->{hash}->{$key}; my $row = ( ref($aryref) eq 'ARRAY' ) ? $aryref : [$aryref]; $meta->{hash}->{$newkey} = $meta->{dbm_mldbm} ? $row : $row->[0]; } # you may not need to explicitly DESTROY the ::Table # put cleanup code to run when the execute is done # sub DESTROY ($) { my $self = shift; my $meta = $self->{meta}; $meta->{hash} and untie %{ $meta->{hash} }; $self->SUPER::DESTROY(); } # truncate() and seek() must be defined to satisfy DBI::SQL::Nano # *IF* you define the *_one_row methods above, truncate() and # seek() can be empty or you can use them without actually # truncating or seeking anything but if you don't define the # *_one_row methods, you may need to define these # if you need to do something after a series of # deletes or updates, you can put it in truncate() # which is called at the end of executing # sub truncate ($$) { # my ( $self, $data ) = @_; return 1; } # seek() is only needed if you use IO::File # though it could be used for other non-file operations # that you need to do before "writes" or truncate() # sub seek ($$$$) { # my ( $self, $data, $pos, $whence ) = @_; return 1; } # Th, th, th, that's all folks! See DBD::File and DBD::CSV for other # examples of creating pure perl DBDs. I hope this helped. # Now it's time to go forth and create your own DBD! # Remember to check in with dbi-dev@perl.org before you get too far. # We may be able to make suggestions or point you to other related # projects. 1; __END__ =pod =head1 NAME DBD::DBM - a DBI driver for DBM & MLDBM files =head1 SYNOPSIS use DBI; $dbh = DBI->connect('dbi:DBM:'); # defaults to SDBM_File $dbh = DBI->connect('DBI:DBM(RaiseError=1):'); # defaults to SDBM_File $dbh = DBI->connect('dbi:DBM:dbm_type=DB_File'); # defaults to DB_File $dbh = DBI->connect('dbi:DBM:dbm_mldbm=Storable'); # MLDBM with SDBM_File # or $dbh = DBI->connect('dbi:DBM:', undef, undef); $dbh = DBI->connect('dbi:DBM:', undef, undef, { f_ext => '.db/r', f_dir => '/path/to/dbfiles/', f_lockfile => '.lck', dbm_type => 'BerkeleyDB', dbm_mldbm => 'FreezeThaw', dbm_store_metadata => 1, dbm_berkeley_flags => { '-Cachesize' => 1000, # set a ::Hash flag }, }); and other variations on connect() as shown in the L docs, L and L shown below. Use standard DBI prepare, execute, fetch, placeholders, etc., see L for an example. =head1 DESCRIPTION DBD::DBM 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, DB_File etc) for improved functionality. The module uses a DBM file storage layer. DBM file storage is common on many platforms and files can be created with it in many programming languages using different APIs. That means, in addition to creating files with DBI/SQL, you can also use DBI/SQL to access and modify files created by other DBM modules and programs and vice versa. B that in those cases it might be necessary to use a common subset of the provided features. DBM files are stored in binary format optimized for quick retrieval when using a key field. That optimization can be used advantageously to make DBD::DBM SQL operations that use key fields very fast. There are several different "flavors" of DBM which use different storage formats supported by perl modules such as SDBM_File and MLDBM. This module supports all of the flavors that perl supports and, when used with MLDBM, supports tables with any number of columns and insertion of Perl objects into tables. DBD::DBM has been tested with the following DBM types: SDBM_File, NDBM_File, ODBM_File, GDBM_File, DB_File, BerkeleyDB. Each type was tested both with and without MLDBM and with the Data::Dumper, Storable, FreezeThaw, YAML and JSON serializers using the DBI::SQL::Nano or the SQL::Statement engines. =head1 QUICK START DBD::DBM operates like all other DBD drivers - it's basic syntax and operation is specified by DBI. If you're not familiar with DBI, you should start by reading L and the documents it points to and then come back and read this file. If you are familiar with DBI, you already know most of what you need to know to operate this module. Just jump in and create a test script something like the one shown below. You should be aware that there are several options for the SQL engine underlying DBD::DBM, see L. There are also many options for DBM support, see especially the section on L. But here's a sample to get you started. use DBI; my $dbh = DBI->connect('dbi:DBM:'); $dbh->{RaiseError} = 1; for my $sql( split /;\n+/," CREATE TABLE user ( user_name TEXT, phone TEXT ); INSERT INTO user VALUES ('Fred Bloggs','233-7777'); INSERT INTO user VALUES ('Sanjay Patel','777-3333'); INSERT INTO user VALUES ('Junk','xxx-xxxx'); DELETE FROM user WHERE user_name = 'Junk'; UPDATE user SET phone = '999-4444' WHERE user_name = 'Sanjay Patel'; SELECT * FROM user "){ my $sth = $dbh->prepare($sql); $sth->execute; $sth->dump_results if $sth->{NUM_OF_FIELDS}; } $dbh->disconnect; =head1 USAGE This section will explain some usage cases in more detail. To get an overview about the available attributes, see L. =head2 Specifying Files and Directories DBD::DBM will automatically supply an appropriate file extension for the type of DBM you are using. For example, if you use SDBM_File, a table called "fruit" will be stored in two files called "fruit.pag" and "fruit.dir". You should B specify the file extensions in your SQL statements. DBD::DBM recognizes following default extensions for following types: =over 4 =item .pag/r Chosen for dbm_type C<< SDBM_File >>, C<< ODBM_File >> and C<< NDBM_File >> when an implementation is detected which wraps C<< -ldbm >> for C<< NDBM_File >> (e.g. Solaris, AIX, ...). For those types, the C<< .dir >> extension is recognized, too (for being deleted when dropping a table). =item .db/r Chosen for dbm_type C<< NDBM_File >> when an implementation is detected which wraps BerkeleyDB 1.x for C<< NDBM_File >> (typically BSD's, Darwin). =back C<< GDBM_File >>, C<< DB_File >> and C<< BerkeleyDB >> don't usually use a file extension. If your DBM type uses an extension other than one of the recognized types of extensions, you should set the I attribute to the extension B file a bug report as described in DBI with the name of the implementation and extension so we can add it to DBD::DBM. Thanks in advance for that :-). $dbh = DBI->connect('dbi:DBM:f_ext=.db'); # .db extension is used $dbh = DBI->connect('dbi:DBM:f_ext='); # no extension is used # or $dbh->{f_ext}='.db'; # global setting $dbh->{f_meta}->{'qux'}->{f_ext}='.db'; # setting for table 'qux' By default files are assumed to be in the current working directory. To use other directories specify the I attribute in either the connect string or by setting the database handle attribute. For example, this will look for the file /foo/bar/fruit (or /foo/bar/fruit.pag for DBM types that use that extension) my $dbh = DBI->connect('dbi:DBM:f_dir=/foo/bar'); # and this will too: my $dbh = DBI->connect('dbi:DBM:'); $dbh->{f_dir} = '/foo/bar'; # but this is recommended my $dbh = DBI->connect('dbi:DBM:', undef, undef, { f_dir => '/foo/bar' } ); # now you can do my $ary = $dbh->selectall_arrayref(q{ SELECT x FROM fruit }); You can also use delimited identifiers to specify paths directly in SQL statements. This looks in the same place as the two examples above but without setting I: my $dbh = DBI->connect('dbi:DBM:'); my $ary = $dbh->selectall_arrayref(q{ SELECT x FROM "/foo/bar/fruit" }); You can also tell DBD::DBM to use a specified path for a specific table: $dbh->{dbm_tables}->{f}->{file} = q(/foo/bar/fruit); Please be aware that you cannot specify this during connection. If you have SQL::Statement installed, you can use table aliases: my $dbh = DBI->connect('dbi:DBM:'); my $ary = $dbh->selectall_arrayref(q{ SELECT f.x FROM "/foo/bar/fruit" AS f }); See the L for using DROP on tables. =head2 Table locking and flock() Table locking is accomplished using a lockfile which has the same basename as the table's file but with the file extension '.lck' (or a lockfile extension that you supply, see below). This lock file is created with the table during a CREATE and removed during a DROP. Every time the table itself is opened, the lockfile is flocked(). For SELECT, this is a shared lock. For all other operations, it is an exclusive lock (except when you specify something different using the I attribute). Since the locking depends on flock(), it only works on operating systems that support flock(). In cases where flock() is not implemented, DBD::DBM will simply behave as if the flock() had occurred although no actual locking will happen. Read the documentation for flock() for more information. Even on those systems that do support flock(), locking is only advisory - as is always the case with flock(). This means that if another program tries to access the table file while DBD::DBM has the table locked, that other program will *succeed* at opening unless it is also using flock on the '.lck' file. As a result DBD::DBM's locking only really applies to other programs using DBD::DBM or other program written to cooperate with DBD::DBM locking. =head2 Specifying the DBM type Each "flavor" of DBM stores its files in a different format and has different capabilities and limitations. See L for a comparison of DBM types. By default, DBD::DBM uses the C<< SDBM_File >> type of storage since C<< SDBM_File >> comes with Perl itself. If you have other types of DBM storage available, you can use any of them with DBD::DBM. It is strongly recommended to use at least C<< DB_File >>, because C<< SDBM_File >> has quirks and limitations and C<< ODBM_file >>, C<< NDBM_File >> and C<< GDBM_File >> are not always available. You can specify the DBM type using the I attribute which can be set in the connection string or with C<< $dbh->{dbm_type} >> and C<< $dbh->{f_meta}->{$table_name}->{type} >> for per-table settings in cases where a single script is accessing more than one kind of DBM file. In the connection string, just set C<< dbm_type=TYPENAME >> where C<< TYPENAME >> is any DBM type such as GDBM_File, DB_File, etc. Do I use MLDBM as your I as that is set differently, see below. my $dbh=DBI->connect('dbi:DBM:'); # uses the default SDBM_File my $dbh=DBI->connect('dbi:DBM:dbm_type=GDBM_File'); # uses the GDBM_File # You can also use $dbh->{dbm_type} to set the DBM type for the connection: $dbh->{dbm_type} = 'DB_File'; # set the global DBM type print $dbh->{dbm_type}; # display the global DBM type If you have several tables in your script that use different DBM types, you can use the $dbh->{dbm_tables} hash to store different settings for the various tables. You can even use this to perform joins on files that have completely different storage mechanisms. # sets global default of GDBM_File my $dbh->('dbi:DBM:type=GDBM_File'); # overrides the global setting, but only for the tables called # I and I my $dbh->{f_meta}->{foo}->{dbm_type} = 'DB_File'; my $dbh->{f_meta}->{bar}->{dbm_type} = 'BerkeleyDB'; # prints the dbm_type for the table "foo" print $dbh->{f_meta}->{foo}->{dbm_type}; B that you must change the I of a table before you access it for first time. =head2 Adding multi-column support with MLDBM Most of the DBM types only support two columns and even if it would support more, DBD::DBM would only use two. However a CPAN module called MLDBM overcomes this limitation by allowing more than two columns. MLDBM does this by serializing the data - basically it puts a reference to an array into the second column. It can also put almost any kind of Perl object or even B into columns. If you want more than two columns, you B install MLDBM. It's available for many platforms and is easy to install. MLDBM is by default distributed with three serializers - Data::Dumper, Storable, and FreezeThaw. Data::Dumper is the default and Storable is the fastest. MLDBM can also make use of user-defined serialization methods or other serialization modules (e.g. L or L. You select the serializer using the I attribute. Some examples: $dbh=DBI->connect('dbi:DBM:dbm_mldbm=Storable'); # use MLDBM with Storable $dbh=DBI->connect( 'dbi:DBM:dbm_mldbm=MySerializer' # use MLDBM with a user defined module ); $dbh=DBI->connect('dbi::dbm:', undef, undef, { dbm_mldbm => 'YAML' }); # use 3rd party serializer $dbh->{dbm_mldbm} = 'YAML'; # same as above print $dbh->{dbm_mldbm} # show the MLDBM serializer $dbh->{f_meta}->{foo}->{dbm_mldbm}='Data::Dumper'; # set Data::Dumper for table "foo" print $dbh->{f_meta}->{foo}->{mldbm}; # show serializer for table "foo" MLDBM works on top of other DBM modules so you can also set a DBM type along with setting dbm_mldbm. The examples above would default to using SDBM_File with MLDBM. If you wanted GDBM_File instead, here's how: # uses DB_File with MLDBM and Storable $dbh = DBI->connect('dbi:DBM:', undef, undef, { dbm_type => 'DB_File', dbm_mldbm => 'Storable', }); SDBM_File, the default I is quite limited, so if you are going to use MLDBM, you should probably use a different type, see L. See below for some L about MLDBM. =head2 Support for Berkeley DB The Berkeley DB storage type is supported through two different Perl modules - DB_File (which supports only features in old versions of Berkeley DB) and BerkeleyDB (which supports all versions). DBD::DBM supports specifying either "DB_File" or "BerkeleyDB" as a I, with or without MLDBM support. The "BerkeleyDB" dbm_type is experimental and it's interface is likely to change. It currently defaults to BerkeleyDB::Hash and does not currently support ::Btree or ::Recno. With BerkeleyDB, you can specify initialization flags by setting them in your script like this: use BerkeleyDB; my $env = new BerkeleyDB::Env -Home => $dir; # and/or other Env flags $dbh = DBI->connect('dbi:DBM:', undef, undef, { dbm_type => 'BerkeleyDB', dbm_mldbm => 'Storable', dbm_berkeley_flags => { 'DB_CREATE' => DB_CREATE, # pass in constants 'DB_RDONLY' => DB_RDONLY, # pass in constants '-Cachesize' => 1000, # set a ::Hash flag '-Env' => $env, # pass in an environment }, }); Do I set the -Flags or -Filename flags as those are determined and overwritten by the SQL (e.g. -Flags => DB_RDONLY is set automatically when you issue a SELECT statement). Time has not permitted us to provide support in this release of DBD::DBM for further Berkeley DB features such as transactions, concurrency, locking, etc. We will be working on these in the future and would value suggestions, patches, etc. See L and L for further details. =head2 Optimizing the use of key fields Most "flavors" of DBM have only two physical columns (but can contain multiple logical columns as explained above in L). They work similarly to a Perl hash with the first column serving as the key. Like a Perl hash, DBM files permit you to do quick lookups by specifying the key and thus avoid looping through all records (supported by DBI::SQL::Nano only). Also like a Perl hash, the keys must be unique. It is impossible to create two records with the same key. To put this more simply and in SQL terms, the key column functions as the I or UNIQUE INDEX. In DBD::DBM, you can take advantage of the speed of keyed lookups by using DBI::SQL::Nano and a WHERE clause with a single equal comparison on the key field. For example, the following SQL statements are optimized for keyed lookup: CREATE TABLE user ( user_name TEXT, phone TEXT); INSERT INTO user VALUES ('Fred Bloggs','233-7777'); # ... many more inserts SELECT phone FROM user WHERE user_name='Fred Bloggs'; The "user_name" column is the key column since it is the first column. The SELECT statement uses the key column in a single equal comparison - "user_name='Fred Bloggs'" - so the search will find it very quickly without having to loop through all the names which were inserted into the table. In contrast, these searches on the same table are not optimized: 1. SELECT phone FROM user WHERE user_name < 'Fred'; 2. SELECT user_name FROM user WHERE phone = '233-7777'; In #1, the operation uses a less-than (<) comparison rather than an equals comparison, so it will not be optimized for key searching. In #2, the key field "user_name" is not specified in the WHERE clause, and therefore the search will need to loop through all rows to find the requested row(s). B that the underlying DBM storage needs to loop over all I pairs when the optimized fetch is used. SQL::Statement has a massively improved where clause evaluation which costs around 15% of the evaluation in DBI::SQL::Nano - combined with the loop in the DBM storage the speed improvement isn't so impressive. Even if lookups are faster by around 50%, DBI::SQL::Nano and SQL::Statement can benefit from the key field optimizations on updating and deleting rows - and here the improved where clause evaluation of SQL::Statement might beat DBI::SQL::Nano every time the where clause contains not only the key field (or more than one). =head2 Supported SQL syntax DBD::DBM uses a subset of SQL. The robustness of that subset depends on what other modules you have installed. Both options support basic SQL operations including CREATE TABLE, DROP TABLE, INSERT, DELETE, UPDATE, and SELECT. B