NAME

POE::Component::EasyDBI - Perl extension for asynchronous non-blocking DBI calls in POE

SYNOPSIS

use POE;
use POE::Component::EasyDBI;

# Set up the DBI
POE::Component::EasyDBI->new(
	alias		=> 'EasyDBI',
	dsn			=> 'DBI:mysql:database=foobaz;host=192.168.1.100;port=3306',
	username	=> 'user',
	password	=> 'pass',
);

# Create our own session to communicate with EasyDBI
POE::Session->create(
	inline_states => {
		_start => sub {
			$kernel->post( 'EasyDBI',
				do => {
					sql => 'DELETE FROM users WHERE user_id = ?',
					placeholders => [ qw( 144 ) ],
					event => 'deleted_handler',
				}
			);

			# 'single' is very different from the single query in SimpleDBI
			# look at 'hash' to get those results
			
			# If you select more than one field, you will only get the last one
			# unless you pass in a seperator with what you want the fields seperated by
			# to get null sperated values, pass in seperator => "\0"
			$kernel->post( 'EasyDBI',
				single => {
					sql => 'Select user_id,user_login from users where user_id = ?',
					event => 'single_handler',
					placeholders => [ qw( 144 ) ],
					seperator => ',', #optional!
				}
			);

			$kernel->post( 'EasyDBI',
				quote => {
					sql => 'foo$*@%%sdkf"""',
					event => 'quote_handler',
				}
			);
			
			$kernel->post( 'EasyDBI',
				arrayhash => {
					sql => 'SELECT user_id,user_login from users where logins = ?',
					event => 'arrayhash_handler',
					placeholders => [ qw( 53 ) ],
				}
			);
			
			my $postback = $_[SESSION]->postback("test",3,2,1);
			
			$_[KERNEL]->post( 'EasyDBI',
				arrayhash => {
					sql => 'SELECT user_id,user_login from users',
					event => 'result_handler',
					extra_data => $postback,
				}
			);

			$_[KERNEL]->post( 'EasyDBI',
				hashhash => {
					sql => 'SELECT * from locations',
					event => 'result_handler',
					primary_key => '1', # you can specify a primary key, or a number based on what column to use
				}
			);
			
			$_[KERNEL]->post( 'EasyDBI',
				hasharray => {
					sql => 'SELECT * from locations',
					event => 'result_handler',
					primary_key => "1",
				}
			);
			
			# you should use limit 1, it is NOT automaticly added
			$_[KERNEL]->post( 'EasyDBI',
				hash => {
					sql => 'SELECT * from locations LIMIT 1',
					event => 'result_handler',
				}
			);
			
			$_[KERNEL]->post( 'EasyDBI',
				array => {
					sql => 'SELECT location_id from locations',
					event => 'result_handler',
				}
			);
			
			$_[KERNEL]->post( 'EasyDBI',
				keyvalhash => {
					sql => 'SELECT location_id,location_name from locations',
					event => 'result_handler',
				}
			);
			# 3 ways to shutdown

			# This will let the existing queries finish, then shutdown
			$kernel->post( 'EasyDBI', 'shutdown' );

			# This will terminate when the event traverses
			# POE's queue and arrives at EasyDBI
			#$kernel->post( 'EasyDBI', shutdown => 'NOW' );

			# Even QUICKER shutdown :)
			#$kernel->call( 'EasyDBI', shutdown => 'NOW' );
		},

		deleted_handler => \&deleted_handler,
		quote_handler	=> \&quote_handler,
		arrayhash_handler => \&arrayhash_handler,
	},
);

sub quote_handler {
	# For QUOTE calls, we receive the scalar string of SQL quoted
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> scalar quoted SQL
	#	placeholders => The placeholders
	#	action => 'QUOTE'
	#	error => Error occurred, check this first
	# }
}

sub deleted_handler {
	# For DO calls, we receive the scalar value of rows affected
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> scalar value of rows affected
	#	placeholders => The placeholders
	#	action => 'do'
	#	error => Error occurred, check this first
	# }
}

sub single_handler {
	# For SINGLE calls, we receive a scalar
	# $_[ARG0] = {
	#	SQL => The SQL you sent
	#	result	=> scalar
	#	placeholders => The placeholders
	#	action => 'single'
	#	seperator => Seperator you may have sent
	#	error => Error occurred, check this first
	# }
}

sub arrayhash_handler {
	# For arrayhash calls, we receive an array of hashes
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> array of hashes
	#	placeholders => The placeholders
	#	action => 'arrayhash'
	#	error => Error occurred, check this first
	# }
}

sub hashhash_handler {
	# For hashhash calls, we receive a hash of hashes
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> hash of hashes keyed on primary key
	#	placeholders => The placeholders
	#	action => 'hashhash'
	#	cols => array of columns in order (to help recreate the sql order)
	#	primary_key => column you specified as primary key, if you specifed a number, the real column name will be here
	#	error => Error occurred, check this first
	# }
}

sub hasharray_handler {
	# For hasharray calls, we receive an hash of arrays
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> hash of hashes keyed on primary key
	#	placeholders => The placeholders
	#	action => 'hashhash'
	#	cols => array of columns in order (to help recreate the sql order)
	#	primary_key => column you specified as primary key, if you specifed a number, the real column name will be here
	#	error => Error occurred, check this first
	# }
}

sub array_handler {
	# For array calls, we receive an array
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> an array, if multiple fields are used, they are comma seperated (specify seperator in event call to change this)
	#	placeholders => The placeholders
	#	action => 'array'
	#	seperator => you sent  # optional!
	#	error => Error occurred, check this first
	# }
}

sub hash_handler {
	# For hash calls, we receive a hash
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> a hash
	#	placeholders => The placeholders
	#	action => 'hash'
	#	error => Error occurred, check this first
	# }
}

sub keyvalhash_handler {
	# For keyvalhash calls, we receive a hash
	# $_[ARG0] = {
	#	sql => The SQL you sent
	#	result	=> a hash  # first field is the key, second field is the value
	#	placeholders => The placeholders
	#	action => 'keyvalhash'
	#	error => Error occurred, check this first
	# }
}

ABSTRACT

This module simplifies DBI usage in POE's multitasking world.

This module is easy to use, you'll have DBI calls in your POE program
up and running in no time.

DESCRIPTION

This module works by creating a new session, then spawning a child process to do the DBI querys. That way, your main POE process can continue servicing other clients.

The standard way to use this module is to do this:

use POE;
use POE::Component::EasyDBI;

POE::Component::EasyDBI->new( ... );

POE::Session->create( ... );

POE::Kernel->run();

Starting EasyDBI

To start EasyDBI, just call it's new method.

This one is for Postgresql:

POE::Component::EasyDBI->new(
	alias		=> 'EasyDBI',
	dsn			=> 'DBI:Pg:dbname=test;host=10.0.1.20',
	username	=> 'user',
	password	=> 'pass',
);

This one is for mysql:

POE::Component::EasyDBI->new(
	alias		=> 'EasyDBI',
	dsn			=> 'DBI:mysql:database=foobaz;host=192.168.1.100;port=3306',
	username	=> 'user',
	password	=> 'pass',
);

This method will die on error or return success.

Note the difference between dbname and database, that is dependant on the driver used, NOT EasyDBI

NOTE: If the SubProcess could not connect to the DB, it will return an error, causing EasyDBI to croak/die.

This constructor accepts 6 different options.

alias

This will set the alias EasyDBI uses in the POE Kernel. This will default TO "EasyDBI"

dsn

This is the DSN (Database connection string)

EasyDBI expects this to contain everything you need to connect to a database via DBI, without the username and password.

For valid DSN strings, contact your DBI driver's manual.

username

This is the DB username EasyDBI will use when making the call to connect

password

This is the DB password EasyDBI will use when making the call to connect

max_retries

This is the max number of times the database wheel will be restarted, default is 5

Events

There is only a few events you can trigger in EasyDBI. They all share a common argument format, except for the shutdown event.

Note: you can change the session that the query posts back to, it uses $_[SENDER] as the default.

For example:

$kernel->post( 'EasyDBI',
	quote => {
			sql => 'foo$*@%%sdkf"""',
			event => 'quoted_handler',
			session => 'dbi_helper', # or you can use a session id
	}
);
quote
This sends off a string to be quoted, and gets it back.

Internally, it does this:

return $dbh->quote( $SQL );

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	quote => {
		sql => 'foo$*@%%sdkf"""',
		event => 'quoted_handler',
	}
);

The Success Event handler will get a hash ref in ARG0:
{
	sql		=>	Unquoted SQL sent
	result	=>	Quoted SQL
}
do
This query is for those queries where you UPDATE/DELETE/etc.

Internally, it does this:

$sth = $dbh->prepare_cached( $sql );
$rows_affected = $sth->execute( $placeholders );
return $rows_affected;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	do => {
		sql => 'DELETE FROM FooTable WHERE ID = ?',
		placeholders => [ qw( 38 ) ],
		event => 'deleted_handler',
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	Scalar value of rows affected
	placeholders	=>	Original placeholders
}
single
This query is for those queries where you will get exactly 1 row and column back.

Internally, it does this:

$sth = $dbh->prepare_cached( $sql );
$sth->bind_columns( %result );
$sth->execute( $placeholders );
$sth->fetch();
return %result;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	single => {
		sql => 'Select test_id from FooTable',
		event => 'result_handler',
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	scalar
	placeholders	=>	Original placeholders
}
arrayhash
This query is for those queries where you will get more than 1 row and column back.

Internally, it does this:

$sth = $dbh->prepare_cached( $SQL );
$sth->execute( $PLACEHOLDERS );
while ( $row = $sth->fetchrow_hashref() ) {
	push( @results,{ %{ $row } } );
}
return @results;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	arrayhash => {
		sql => 'SELECT this, that FROM my_table WHERE my_id = ?',
		event => 'result_handler',
		placeholders => [ qw( 2021 ) ],
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	Array of hashes of the rows ( array of fetchrow_hashref's )
	placeholders	=>	Original placeholders
	cols			=>	An array of the cols in query order
}
hashhash
This query is for those queries where you will get more than 1 row and column back.

The primary_key should be UNIQUE! If it is not, then use hasharray instead.

Internally, it does something like this:

if ($primary_key =~ m/^\d+$/) {
	if ($primary_key} > $sth->{NUM_OF_FIELDS}) {
		die "primary_key is out of bounds";
	}
	$primary_key = $sth->{NAME}->[($primary_key-1)];
}

for $i ( 0 .. $sth->{NUM_OF_FIELDS}-1 ) {
	$col{$sth->{NAME}->[$i]} = $i;
	push(@cols, $sth->{NAME}->[$i]);
}

$sth = $dbh->prepare_cached( $SQL );
$sth->execute( $PLACEHOLDERS );
while ( @row = $sth->fetch_array() ) {
	foreach $c (@cols) {
		$results{$row[$col{$primary_key}]}{$c} = $row[$col{$c}];
	}
}
return %results;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	hashhash => {
		sql => 'SELECT this, that FROM my_table WHERE my_id = ?',
		event => 'result_handler',
		placeholders => [ qw( 2021 ) ],
		primary_key => "2",  # making 'that' the primary key
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	Hashes of hashes of the rows
	placeholders	=>	Original placeholders
	cols			=>	An array of the cols in query order
}
hasharray
This query is for those queries where you will get more than 1 row and column back.

Internally, it does something like this:

# find the primary key
if ($primary_key =~ m/^\d+$/) {
	if ($primary_key} > $sth->{NUM_OF_FIELDS}) {
		die "primary_key is out of bounds";
	}
	$primary_key = $sth->{NAME}->[($primary_key-1)];
}

for $i ( 0 .. $sth->{NUM_OF_FIELDS}-1 ) {
	$col{$sth->{NAME}->[$i]} = $i;
	push(@cols, $sth->{NAME}->[$i]);
}

$sth = $dbh->prepare_cached( $SQL );
$sth->execute( $PLACEHOLDERS );
while ( @row = $sth->fetch_array() ) {
	push(@{ $results{$row[$col{$primary_key}}]} }, @row);
}
return %results;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	hasharray => {
		sql => 'SELECT this, that FROM my_table WHERE my_id = ?',
		event => 'result_handler',
		placeholders => [ qw( 2021 ) ],
		primary_key => "1",  # making 'this' the primary key
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	Hashes of hashes of the rows
	placeholders	=>	Original placeholders
	primary_key		=>	'this' # the column name for the number passed in
	cols			=>	An array of the cols in query order
}
array
This query is for those queries where you will get more than 1 row with 1 column back.

Internally, it does this:

$sth = $dbh->prepare_cached( $SQL );
$sth->execute( $PLACEHOLDERS );
while ( @row = $sth->fetchrow_array() ) {
	if ($seperator) {
		push( @results,join($seperator,@row) );
	} else {
		push( @results,join(',',@row) );
	}
}
return @results;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	array => {
		sql => 'SELECT this FROM my_table WHERE my_id = ?',
		event => 'result_handler',
		placeholders => [ qw( 2021 ) ],
		seperator => ',', # default seperator
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	Array of scalars (joined with seperator if more than one column is returned)
	placeholders	=>	Original placeholders
}
hash
This query is for those queries where you will get 1 row with more than 1 column back.

Internally, it does this:

$sth = $dbh->prepare_cached( $SQL );
$sth->execute( $PLACEHOLDERS );
@row = $sth->fetchrow_array();
if (@row) {
	for $i ( 0 .. $sth->{NUM_OF_FIELDS}-1 ) {
		$results{$sth->{NAME}->[$i]} = $row[$i];
	}
}
return %results;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	hash => {
		sql => 'SELECT * FROM my_table WHERE my_id = ?',
		event => 'result_handler',
		placeholders => [ qw( 2021 ) ],
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	Hash
	placeholders	=>	Original placeholders
}
keyvalhash
This query is for those queries where you will get 1 row with more than 1 column back.

Internally, it does this:

$sth = $dbh->prepare_cached( $SQL );
$sth->execute( $PLACEHOLDERS );
while (	@row = $sth->fetchrow_array() ) {
	$results{$row[0]} = $row[1];
}
return %results;

Here's an example on how to trigger this event:

$kernel->post( 'EasyDBI',
	keyvalhash => {
		sql => 'SELECT this, that FROM my_table WHERE my_id = ?',
		event => 'result_handler',
		placeholders => [ qw( 2021 ) ],
	}
);

The Success Event handler will get a hash in ARG0:
{
	sql				=>	SQL sent
	result			=>	Hash
	placeholders	=>	Original placeholders
}
shutdown
$kernel->post( 'EasyDBI', 'shutdown' );

This will signal EasyDBI to start the shutdown procedure.

NOTE: This will let all outstanding queries run!
EasyDBI will kill it's session when all the queries have been processed.

you can also specify an argument:

$kernel->post( 'EasyDBI', 'shutdown' => 'NOW' );

This will signal EasyDBI to shutdown.

NOTE: This will NOT let the outstanding queries finish!
Any queries running will be lost!

Due to the way POE's queue works, this shutdown event will take some time to propagate POE's queue.
If you REALLY want to shut down immediately, do this:

$kernel->call( 'EasyDBI', 'shutdown' => 'NOW' );

ALL shutdown NOW's send kill -9 to thier children, beware of any transactions that you may be in.
Your queries will revert if you are in transaction mode

Arguments

They are passed in via the $kernel->post( ... );

Note: all query types can be in ALL-CAPS or lowercase but not MiXeD!

ie ARRAYHASH or arrayhash but not ArrayHash

sql

This is the actual SQL line you want EasyDBI to execute. You can put in placeholders, this module supports them.

placeholders

This is an array of placeholders.

You can skip this if your query does not use placeholders in it.

event

This is the success/failure event, triggered whenever a query finished successfully or not.

It will get a hash in ARG0, consult the specific queries on what you will get.

In the case of an error, the key 'error' will have the specific error that occurred

seperator

Query types single, and array accept this parameter. The default is a comma (,) and is optional

If a query has more than 1 column returned, the columns are joined with 'seperator'.

primary_key

Query types hashhash, and hasharray accept this parameter. It is used to key the hash on a certain field

chunked

All multi-row queries can be chunked.

You can pass the parameter 'chunked' with a number of rows to fire the 'event' event for every 'chunked' rows, it will fire the 'event' event. ( a 'chunked' key will exist ) A 'last_chunk' key will exist when you have received the last chunk of data from the query

EasyDBI Notes

This module is very picky about capitalization!

All of the options are in lowercase. Query types can be in ALL-CAPS or lowercase.

This module will try to keep the SubProcess alive. if it dies, it will open it again for a max of 5 retries by default, but you can override this behavior by doing something like this:

POE::Component::EasyDBI->new( max_retries => 3 );

EXPORT

Nothing.

SEE ALSO

DBI

POE

POE::Wheel::Run

POE::Component::DBIAgent

POE::Component::LaDBI

POE::Component::SimpleDBI

AUTHOR

David Davis <xantus@cpan.org>

CREDITS

Apocalypse <apocal@cpan.org> for POE::Component::SimpleDBI the basis of this PoCo

COPYRIGHT AND LICENSE

Copyright 2003 by David Davis and Teknikill Software

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