AddressBook

 view release on metacpan or  search on metacpan

lib/AddressBook/DB/DBI.pm  view on Meta::CPAN

=item key_fields

A list of DBI field names (not cannonical names) which can be used to uniquely
identify a database record.

=item dsn

See constructor details below

=back

=cut

use strict;
use DBI;
use AddressBook;
use AddressBook::Entry;
use Carp;
use File::Basename;
use Date::Manip;
use vars qw($VERSION @ISA);

$VERSION = '0.13';

@ISA = qw(AddressBook);

=head2 new

The database driver and driver arguments may be specified in in the constructor
in one of two ways: 

=over 4

=item 1

As part of the "source" parameter, for example:

  $a = AddressBook->new(source => "DBI:CSV:f_dir=/tmp/csv",
			table=>"a_csv",
			);

=item 2

In a "dsn" parameter, for example:

  $a = AddressBook->new(source => "DBI",
			dsn=>"CSV:f_dir=/tmp/csv",
			table=>"a_csv",
			);

Like all AddressBook database constructor parameters, the "dsn" and "table" may 
also be specified in the configuration file.

=back

=cut

sub new {
  my $class = shift;
  my $self = {};
  bless ($self,$class);
  my %args = @_;
  foreach (keys %args) {
    $self->{$_} = $args{$_};
  }
  if(defined $self->{dsn}) {
    ($self->{dbi_driver},$self->{dsn}) = split (':',$self->{dsn});
    my $dbh = DBI->connect("dbi:" . $self->{dbi_driver} . ":" . $self->{dsn}) 
	|| croak $self->{dbh}->errstr;
    $self->{dbh} = $dbh;
  }
  if (! defined $self->{intra_attr_sep_char}) {
    $self->{intra_attr_sep_char} = ';';
  }
  $self->_verify_table;
  return $self;
}

sub _verify_table {
  my $self = shift;
  my $class = ref $self || croak "Not a method call";
  if ($self->{dbi_driver} eq "CSV") {
    my @tables = $self->{dbh}->func('list_tables');
    my $found = 0;
    foreach (@tables) {
      if ($_ eq $self->{table}) {
	$found=1;
	last;
      }
    }
    if (! $found) {croak "table \"$self->{table}\" does not exist"}
  } else {
    croak "Cannot verify table";
  }
}

sub DESTROY {
  my $self = shift;
  my $class = ref $self || croak "Not a method call";

  $self->{dbh}->disconnect;
}

sub search {
  my $self = shift;
  my $class = ref $self || croak "Not a method call";
  my @ret;
  my %arg = @_;
  my ($filter,@filter,$count);
  my $op = "select * from " . $self->{table};
  if(defined $arg{filter}) {
    my $entry = AddressBook::Entry->new(attr=>{%{$arg{filter}}},
					config => $self->{config},
					);
    $entry = $entry->get(db=>$self->{db_name},values_only=>'1');
    foreach (keys %{$entry}) {
      push @filter,"$_ = ".$self->{dbh}->quote(join ($self->{intra_attr_sep_char},@{$entry->{$_}}));
    }
    $filter = join " AND ",@filter;
    $op .= " where $filter";
  }



( run in 0.756 second using v1.01-cache-2.11-cpan-39bf76dae61 )