DB_File::DB_Database - Perl module for reading and writing the DB_File data as a mutifield table with index file supported.

- NAME
- SYNOPSIS
- DESCRIPTION

- General methods
- Using it as key /values(list)
- Writing the data
- Using it as Table
- Writing the data
- Using Index
- Select records
- Dumping the content of the file
- Error Message

- BUGS
- DATA TYPES
- LOCKING
- VERSION
- AUTHOR
- SEE ALSO

# NAME

DB_File::DB_Database - Perl module for reading and writing the DB_File data as a mutifield table with index file supported.

# SYNOPSIS

      use DB_File::DB_Database;
      my $table   = new DB_File::DB_Database "dbexample" or die DB_File::DB_Database->errstr;

      my @data    = $table->get_record("Judy");
      my $hashref = $table->get_record_hash('James');

      $table->append_record("Caroline", "20", "sister");
      $table->append_record_hash('jimmy', "age" => 25,
      $table->set_record("Judy", "18", "a beauty");
      $table->set_record_hash('Roger', "age" => 25,"msg" => 'everything is easy!');
      $table->update_record_hash("Roger", "MSG" => "New message");
      $table->delete_record("Roger");

      $table->prepare_select( "seek"  => {'index'=> 'indexA',
                                          'from' => 10,
                                          'to'   => 25},
                              "where" => {'msg'=> 'hi'},
                              "top"   => 10);
      $table->dump_data;
      $table->close;

# DESCRIPTION

This module can handle DB_File data(DB_HASH, key/value pairs) as a mutifield table. It also can create auto updated index `files(DB_BTREE)` to faster the searching speed. It is an Beta version, use it at your own risk.

The following methods are supported by DB_File::DB_Database module:

## General methods

new
  Creates the DB_File::DB_Database object, loads the info about the table form the database file. The first parameter could be the name of an existing file (table, in fact). (A suffix .db will be appended if needed.) This method creates and initializes new object, will also open the index files, if needed.

  The parameters can also be specified in the form of hash: value of name is then the name of the table, other flags supported are:

  readonly open the database file and the index files only for reading

          my $table = new DB_File::DB_Database "dbexample" or die DB_File::DB_Database->errstr;
          my $table = new DB_File::DB_Database "name" => "dbexample","readonly" => 1;

open
  Same as new method.

          my $table = new DB_File::DB_Database;
          $table->open ("name" => "dbexample","readonly" => 1) or die DB_File::DB_Database->errstr;

close
  Closes the object/file, no arguments.

create
  Creates new database file on disk and initializes it with 0 records. Parameters to create are passed as hash. Each being a reference to list: field_names, field_types. The field types are specified by one letter strings (C, N). If you set some value as undefined, create will make that field to C. Note that the field type does not actually take effect, it is only used when indexing the field. (To know index it as a string or a number.) Please do not use field names begin with ``__'', it is reserved by DB_File::DB_Database. Default permits of the file is 0640.

          my $newtable = DB_File::DB_Database->create( "name"        => "dbexample",
                                              "field_names" => [ "Age", "MSG" ],
                                              "field_types" => [ "N", "C" ],
                                              'permits'     => 0640 );

  The new file mustn't exist yet -- DB_File::DB_Database will not allow you to overwrite existing table. Use drop (or unlink) to delete it first.

drop
  This method closes the table and deletes it on disk (including associated index file, if there is any).

field_names, field_types
  Return list of field names and so on for the data file.

rows
  Return the sum number of records.

## Using it as key /values(list)

More than key/value pairs, DB_File::DB_Database can make key / `values(list)` pairs.

get_record
  Returns a list of data (field values) from the specified record (a unique ID of the line, not one of the field names). The first parameter in the call is the ID of the record. If you do not specify any other parameters, all fields are returned in the same order as they appear in the file. You can also put list of field names after the record number and then only those will be returned. The first value of the returned list is always the ID of the record. If ID not found, get_record returns empty list.

get_record_nf
  Instead if the names of the fields, you can pass list of numbers of the fields to read.

get_record_hash
  Returns hash (in list context) or reference to hash (in scalar context) containing field values indexed by field names. The only parameter in the call is the ID. The field names are returned as uppercase. The unique ID is put in to field name ``__ID''.

## Writing the data

On success they return true -- the record ID. Index file is automatical updated, if needed.

set_record
  As parameters, takes the ID of the record and the list of values of the fields. It writes the record to the file. Unspecified fields (if you pass less than you should) are set to undef/empty.

set_record_hash
  Takes number of the record and hash as parameters, sets the fields, unspecified are undefed/emptied.

update_record_hash
  Like set_record_hash but fields that do not have value specified in the hash retain their value.

delete_record
  Delete the `record(s)` by the ID(s). Return a number of how many records is deleted.

Examples of reading and writing:

        $table->set_record("Judy", "18", "a beauty");
        my @data = $table->get_record("Judy");
        my $hashref = $table->get_record_hash('James');
        $table->set_record_hash('Roger', "age" => 25,
                                            "msg" => 'everything is easy!');

This is a code to update field MSG in record where record ID is ``Roger''.

        use DB_File::DB_Database;
        my $table = new DB_File::DB_Database "dbexample" or die DB_File::DB_Database->errstr;
        my ($id, $age) = $table->get_record("Roger", "age")
        die $table->errstr unless defined $id;
        $table->update_record_hash("Roger", "MSG" => "New message");

## Using it as Table

get_record
  the same

get_record_nf
  the same

get_record_hash
  the same

## Writing the data

Basically like above, but do not specify the ID, leave it to DB_File::DB_Database. The ID will be sequent numbers. On success they return true -- the record ID. Index file is automatical updated, if needed.

set_record
  the same, recommand to use for updating data

set_record_hash
  the same, recommand to use for updating data

update_record_hash
  the same

delete_record
  the same

append_record
  As parameters, takes the list of values of the fields. It append the record to the file. Unspecified fields (if you pass less than you should) are set to undef/empty. ID will be returned.

append_record_hash
  Unspecified fields (if you pass less than you should) are set to undef/empty. ID will be returned.

Examples:

        $table->append_record("Caroline", "20", "sister");
        $table->append_record_hash('jimmy', "age" => 25,
                                            "msg" => 'Nothing is easy!');

## Using Index

Index file is stored in DB_File BTREE. Once created, all index files will be automatically opened when open the database file, and updated automatically when writing the database file.

create_index
  Create index file for one field. Default permits of the index file is 0640. 'name' is the index tag name, 'key' is the formula for indexing. For example:

        'key' => 'Age'            # index by the age, from young to old
        'key' => '-Age'           # index by the age, from old to young
        'key' => '-Age(3)+Name'   # index by the age(up to 999),then name; from old to young,then from A to Z
        'key' => '-Age(3)+-Name'  # index by the age(up to 999),then name; from old to young,then from Z to A

  'Age(3)' is similar to 'substr(Age,0,3)', only the length of the last field name appeared in the 'key' can be ommited. '+-' CAN'T be subsituded by '-'.

        # Index File name will be dbexample_indexA
        print $table->create_index( 'name'   => 'indexA' ,
                                    'key'    => 'Age' ,       # '-Age' means reverse sort,
                                    'permits'=> 0640 );

recreate_index
  Recreate the index file. Parameter is the index name(s).

drop_index
  Delete the index file. Parameter is the index name(s).

        # delete Index indexA
        print $table->drop_index('indexA');

## Select records

Select matched records, using index will speed up the searching.

prepare_select
  As parameters, pass a hash as parameters. Almost each value is a hash reference. Eg: # find people aged form 10 to 25, select the first 10 people. their 'msg' must content 'hi' $table->prepare_select( ``seek'' => {'index'=> 'indexA', 'from' => 10, 'to' => 25}, ``where'' => {'msg'=> 'hi'}, ``top'' => 10);

  If no ``seek'' specified(do not use index), it will search from the first record to the last(or up to the record numbers you needed).``top'' means select the first ? records. You may use ``cut'' instead, ``cut'' => [2,6] means select from the secord matched record till to the sixth.

  for ``seek'', ``from'' is needed, ``to'' can be omitted(till the last).

  To fetch the selected record. Use get_record, get_record_nf, get_record_hash, leave the ID undef.

Examples of selecting record:

        use DB_File::DB_Database;
        my $table = new DB_File::DB_Database "dbexample" or die DB_File::DB_Database->errstr;
        my $table = new XBase "names.dbf" or die XBase->errstr;
        # find people aged form 10 to 25, select the first 10 people. their 'msg' must content 'hi'
        $table->prepare_select( "seek"  => {'index'=> 'indexA',
                                            'from' => 10,
                                            'to'   => 25},
                                "where" => {'msg'=> 'hi'},
                                "top"   => 10);
        while ( @_ = $table->get_record(undef,'age','msg') ){
             ### do something here
             print ++$i,"\n";
             print "@_ ","\n";
        }

## Dumping the content of the file

print the database file records and the index files contenting.

dump_data
  Record separator, string, newline by default.

  Example of use is

          $table->dump_data;

dump_all
  dump the object (only for debuging) (Data::Dump is needed)

## Error Message

if the method fails (returns false or null list), the error message can be retrieved via errstr method. If the new or create method fails, you have no object so you get the error message using class syntax DB_File::DB_Database->errstr().

# BUGS

After create_index or recreate_index, file should be closed then open again. or something strange will happed.

if you found any bugs or make any patches, I would be appriciate to hear from you.

# DATA TYPES

Use `DB_File(DB_HASH)` to store data (key/value pairs). Value use a CSV (comma separated text) to store a list. No character limits. DB_File::DB_Database do NOT need TEXT::CSV or TEXT::CSV_XS. but you can easily changed it to that modules.

Index files are stored as DB_File (DB_BTREE). Key is the text, value is the ID.

# LOCKING

The locking is a poor. Every opened file has a '_lock' file(non Windows). But No locking is done. No extra locking in Windows.

# VERSION

0.03

publish time: 2001.05.16

# AUTHOR

(c) 2001 冉宁煜 / Ran Ningyu, <rny@163.net> http://perl.yesky.net/ or http://www.skybamboo.com/perl/ at SouthEast University, Nanjing, China.

All rights reserved. This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

# SEE ALSO

DB_File