package DBD::Mock; # --------------------------------------------------------------------------- # # Copyright (c) 2004-2007 Stevan Little, Chris Winters # (spawned from original code Copyright (c) 1994 Tim Bunce) # --------------------------------------------------------------------------- # # You may distribute under the terms of either the GNU General Public # License or the Artistic License, as specified in the Perl README file. # --------------------------------------------------------------------------- # use 5.008001; use strict; use warnings; use DBI; use DBD::Mock::dr; use DBD::Mock::db; use DBD::Mock::st; use DBD::Mock::StatementTrack; use DBD::Mock::StatementTrack::Iterator; use DBD::Mock::Session; use DBD::Mock::Pool; use DBD::Mock::Pool::db; sub import { shift; $DBI::connect_via = "DBD::Mock::Pool::connect" if ( @_ && lc( $_[0] ) eq "pool" ); } our $VERSION = '1.60'; our $drh = undef; # will hold driver handle our $err = 0; # will hold any error codes our $errstr = ''; # will hold any error messages # Defaulting a result set's fields to undef changes the way DBD::Mock responds, so we default it to off our $DefaultFieldsToUndef = 0; sub driver { return $drh if defined $drh; my ( $class, $attributes ) = @_; $attributes = {} unless ( defined($attributes) && ( ref($attributes) eq 'HASH' ) ); $drh = DBI::_new_drh( "${class}::dr", { Name => 'Mock', Version => $DBD::Mock::VERSION, Attribution => 'DBD Mock driver by Chris Winters & Stevan Little (orig. from Tim Bunce)', Err => \$DBD::Mock::err, Errstr => \$DBD::Mock::errstr, # mock attributes mock_connect_fail => 0, # and pass in any extra attributes given %{$attributes} } ); return $drh; } sub CLONE { undef $drh } # NOTE: # this feature is still quite experimental. It is defaulted to # be off, but it can be turned on by doing this: # $DBD::Mock::AttributeAliasing++; # and then turned off by doing: # $DBD::Mock::AttributeAliasing = 0; # we shall see how this feature works out. our $AttributeAliasing = 0; my %AttributeAliases = ( mysql => { db => { # aliases can either be a string which is obvious mysql_insertid => 'mock_last_insert_id' }, st => { # but they can also be a subroutine reference whose # first argument will be either the $dbh or the $sth # depending upon which context it is aliased in. mysql_insertid => sub { (shift)->{Database}->{'mock_last_insert_id'} } } }, mariadb => { db => { mariadb_insertid => 'mock_last_insert_id' }, st => { mariadb_insertid => sub { (shift)->{Database}->{'mock_last_insert_id'} } } } ); sub _get_mock_attribute_aliases { my ($dbname) = @_; ( exists $AttributeAliases{ lc($dbname) } ) || die "Attribute aliases not available for '$dbname'"; return $AttributeAliases{ lc($dbname) }; } sub _set_mock_attribute_aliases { my ( $dbname, $dbh_or_sth, $key, $value ) = @_; return $AttributeAliases{ lc($dbname) }->{$dbh_or_sth}->{$key} = $value; } ## Some useful constants use constant NULL_RESULTSET => [ [] ]; 1; __END__ =head1 NAME DBD::Mock - Mock database driver for testing =head1 SYNOPSIS use DBI; # connect to your as normal, using 'Mock' as your driver name my $dbh = DBI->connect( 'DBI:Mock:', '', '' ) || die "Cannot create handle: $DBI::errstr\n"; # create a statement handle as normal and execute with parameters my $sth = $dbh->prepare( 'SELECT this, that FROM foo WHERE id = ?' ); $sth->execute( 15 ); # Now query the statement handle as to what has been done with it my $mock_params = $sth->{mock_params}; print "Used statement: ", $sth->{mock_statement}, "\n", "Bound parameters: ", join( ', ', @{ $mock_params } ), "\n"; =head1 DESCRIPTION Testing with databases can be tricky. If you are developing a system married to a single database then you can make some assumptions about your environment and ask the user to provide relevant connection information. But if you need to test a framework that uses DBI, particularly a framework that uses different types of persistence schemes, then it may be more useful to simply verify what the framework is trying to do -- ensure the right SQL is generated and that the correct parameters are bound. C makes it easy to just modify your configuration (presumably held outside your code) and just use it instead of C (like L or L) in your framework. There is no distinct area where using this module makes sense. (Some people may successfully argue that this is a solution looking for a problem...) Indeed, if you can assume your users have something like L or L or if you do not mind creating a dependency on them then it makes far more sense to use these legitimate driver implementations and test your application in the real world -- at least as much of the real world as you can create in your tests... And if your database handle exists as a package variable or something else easily replaced at test-time then it may make more sense to use L to create a fully dynamic handle. There is an excellent article by chromatic about using L in this and other ways, strongly recommended. (See L for a link) =head2 How does it work? C comprises a set of classes used by DBI to implement a database driver. But instead of connecting to a datasource and manipulating data found there it tracks all the calls made to the database handle and any created statement handles. You can then inspect them to ensure what you wanted to happen actually happened. For instance, say you have a configuration file with your database connection information: [DBI] dsn = DBI:Pg:dbname=myapp user = foo password = bar And this file is read in at process startup and the handle stored for other procedures to use: package ObjectDirectory; my ( $DBH ); sub run_at_startup { my ( $class, $config ) = @_; $config ||= read_configuration( ... ); my $dsn = $config->{DBI}{dsn}; my $user = $config->{DBI}{user}; my $pass = $config->{DBI}{password}; $DBH = DBI->connect( $dsn, $user, $pass ) || die ...; } sub get_database_handle { return $DBH; } A procedure might use it like this (ignoring any error handling for the moment): package My::UserActions; sub fetch_user { my ( $class, $login ) = @_; my $dbh = ObjectDirectory->get_database_handle; my $sql = q{ SELECT login_name, first_name, last_name, creation_date, num_logins FROM users WHERE login_name = ? }; my $sth = $dbh->prepare( $sql ); $sth->execute( $login ); my $row = $sth->fetchrow_arrayref; return ( $row ) ? User->new( $row ) : undef; } So for the purposes of our tests we just want to ensure that: =over 4 =item 1. The right SQL is being executed =item 2. The right parameters are bound =back Assume whether the SQL actually B or not is irrelevant for this test :-) To do that our test might look like: my $config = ObjectDirectory->read_configuration( ... ); $config->{DBI}{dsn} = 'DBI:Mock:'; ObjectDirectory->run_at_startup( $config ); my $login_name = 'foobar'; my $user = My::UserActions->fetch_user( $login_name ); # Get the handle from ObjectDirectory; # this is the same handle used in the # 'fetch_user()' procedure above my $dbh = ObjectDirectory->get_database_handle(); # Ask the database handle for the history # of all statements executed against it my $history = $dbh->{mock_all_history}; # Now query that history record to # see if our expectations match reality is(scalar(@{$history}), 1, 'Correct number of statements executed' ; my $login_st = $history->[0]; like($login_st->statement, qr/SELECT login_name.*FROM users WHERE login_name = ?/sm, 'Correct statement generated' ); my $params = $login_st->bound_params; is(scalar(@{$params}), 1, 'Correct number of parameters bound'); is($params->[0], $login_name, 'Correct value for parameter 1' ); # Reset the handle for future operations $dbh->{mock_clear_history} = 1; The list of properties and what they return is listed below. But in an overall view: =over 4 =item * A database handle contains the history of all statements created against it. Other properties set for the handle (e.g., C, C) are left alone and can be queried as normal, but they do not affect anything. (A future feature may track the sequence/history of these assignments but if there is no demand it probably will not get implemented.) =item * A statement handle contains the statement it was prepared with plus all bound parameters or parameters passed via C. It can also contain predefined results for the statement handle to C, track how many fetches were called and what its current record is. =back =head2 A Word of Warning This may be an incredibly naive implementation of a DBD. But it works for me... =head1 DBD::Mock Since this is a normal DBI statement handle we need to expose our tracking information as properties (accessed like a hash) rather than methods. =head2 Database Driver Properties =over 4 =item B> This is a boolean property which when set to true (C<1>) will not allow DBI to connect. This can be used to simulate a DSN error or authentication failure. This can then be set back to false (C<0>) to resume normal DBI operations. Here is an example of how this works: # install the DBD::Mock driver my $drh = DBI->install_driver('Mock'); $drh->{mock_connect_fail} = 1; # this connection will fail my $dbh = DBI->connect('dbi:Mock:', '', '') || die "Cannot connect"; # this connection will throw an exception my $dbh = DBI->connect('dbi:Mock:', '', '', { RaiseError => 1 }); $drh->{mock_connect_fail} = 0; # this will work now ... my $dbh = DBI->connect(...); This feature is conceptually different from the C attribute of the C<$dbh> in that it has a driver-wide scope, where C is handle-wide scope. It also only prevents the initial connection, any C<$dbh> handles created prior to setting C to true (C<1>) will still go on working just fine. =item B> This is an ARRAY reference which holds fake data sources which are returned by the Driver and Database Handle's C method. =item B> This takes a string and adds it to the C attribute. =back =head2 Database Handle Properties =over 4 =item B> Returns an array reference with all history (a.k.a. C) objects created against the database handle in the order they were created. Each history object can then report information about the SQL statement used to create it, the bound parameters, etc.. =item B> Returns a C object which will iterate through the current set of C object in the history. See the L documentation below for more information. =item B> If set to a true value all previous statement history operations will be erased. This B the history of currently open handles, so if you do something like: my $dbh = get_handle( ... ); my $sth = $dbh->prepare( ... ); $dbh->{mock_clear_history} = 1; $sth->execute( 'Foo' ); You will have no way to learn from the database handle that the statement parameter 'Foo' was bound. This is useful mainly to ensure you can isolate the statement histories from each other. A typical sequence will look like: set handle to framework perform operations analyze mock database handle reset mock database handle history perform more operations analyze mock database handle reset mock database handle history ... =item B> This statement allows you to simulate a downed database connection. This is useful in testing how your application/tests will perform in the face of some kind of catastrophic event such as a network outage or database server failure. It is a simple boolean value which defaults to on, and can be set like this: # turn the database off $dbh->{mock_can_connect} = 0; # turn it back on again $dbh->{mock_can_connect} = 1; The statement handle checks this value as well, so something like this will fail in the expected way: $dbh = DBI->connect( 'DBI:Mock:', '', '' ); $dbh->{mock_can_connect} = 0; # blows up! my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) }); if ( $@ ) { # Here, $DBI::errstr = 'No connection present' } Turning off the database after a statement prepare will fail on the statement C, which is hopefully what you would expect: $dbh = DBI->connect( 'DBI:Mock:', '', '' ); # ok! my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) }); $dbh->{mock_can_connect} = 0; # blows up! $sth->execute; Similarly: $dbh = DBI->connect( 'DBI:Mock:', '', '' ); # ok! my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) }); # ok! $sth->execute; $dbh->{mock_can_connect} = 0; # blows up! my $row = $sth->fetchrow_arrayref; Note: The handle attribute C and the handle method C will behave according to the value of C. So if C were to be set to C<0> (or off), then both C and C would return false values (or C<0>). =item B> This stocks the database handle with a record set, allowing you to seed data for your application to see if it works properly. Each recordset is a simple arrayref of arrays with the first arrayref being the field names used. Every time a statement handle is created it asks the database handle if it has any resultsets available and if so uses it. Here is a sample usage, partially from the test suite: my @user_results = ( [ 'login', 'first_name', 'last_name' ], [ 'cwinters', 'Chris', 'Winters' ], [ 'bflay', 'Bobby', 'Flay' ], [ 'alincoln', 'Abe', 'Lincoln' ], ); my @generic_results = ( [ 'foo', 'bar' ], [ 'this_one', 'that_one' ], [ 'this_two', 'that_two' ], ); my $dbh = DBI->connect( 'DBI:Mock:', '', '' ); $dbh->{mock_add_resultset} = \@user_results; # add first resultset $dbh->{mock_add_resultset} = \@generic_results; # add second resultset my ( $sth ); eval { $sth = $dbh->prepare( 'SELECT login, first_name, last_name FROM foo' ); $sth->execute(); }; # this will fetch rows from the first resultset... my $row1 = $sth->fetchrow_arrayref; my $user1 = User->new( login => $row->[0], first => $row->[1], last => $row->[2] ); is( $user1->full_name, 'Chris Winters' ); my $row2 = $sth->fetchrow_arrayref; my $user2 = User->new( login => $row->[0], first => $row->[1], last => $row->[2] ); is( $user2->full_name, 'Bobby Flay' ); ... my $sth_generic = $dbh->prepare( 'SELECT foo, bar FROM baz' ); $sth_generic->execute; # this will fetch rows from the second resultset... my $row = $sth->fetchrow_arrayref; It is possible to assign a hashref where the resultset must be given as value for the C key: $dbh->{mock_add_resultset} = { results => [ [ 'foo', 'bar' ], [ 'this_one', 'that_one' ], [ 'this_two', 'that_two' ], ], }; The reason for the hashref form is that you can add options as described in the following. You can associate a resultset with a particular SQL statement instead of adding them in the order they will be fetched: $dbh->{mock_add_resultset} = { sql => 'SELECT foo, bar FROM baz', results => [ [ 'foo', 'bar' ], [ 'this_one', 'that_one' ], [ 'this_two', 'that_two' ], ], }; This will return the given results when the statement 'C statements to ensure that placeholders are bound properly. And typically you may simply want to check after the fact that a statement is syntactically correct, or at least what you expect. But other times you may want to parse the statement as it is prepared rather than after the fact. There is a hook in this mock database driver for you to provide your own parsing routine or object. The syntax is simple: $dbh->{mock_add_parser} = sub { my ( $sql ) = @_; unless ( $sql =~ /some regex/ ) { die "does not contain secret fieldname"; } }; You can also add more than one for a handle. They will be called in order, and the first one to fail will halt the parsing process: $dbh->{mock_add_parser} = \&parse_update_sql; $dbh->{mock_add-parser} = \&parse_insert_sql; Depending on the C and C settings in the database handle any parsing errors encountered will issue a C or C. No matter what the statement handle will be C. Instead of providing a subroutine reference you can use an object. The only requirement is that it implements the method C and takes a SQL statement as the only argument. So you should be able to do something like the following (untested): my $parser = SQL::Parser->new( 'mysql', { RaiseError => 1 } ); $dbh->{mock_add_parser} = $parser; =item B> & B> These properties will dispatch to the Driver's properties of the same name. =back =head2 Attribute Aliasing Basically this feature allows you to alias attributes to other attributes. So for instance, you can alias a commonly expected attribute like C to something C already has like C. While you can also just set C yourself, this functionality allows it to take advantage of things like the autoincrementing of the C attribute. The functionality is off by default so as to not cause any issues with backwards compatibility, but can easily be turned on and off like this: # turn it on $DBD::Mock::AttributeAliasing++; # turn it off $DBD::Mock::AttributeAliasing = 0; Once this is turned on, you will need to choose a database specific attribute aliasing table like so: DBI->connect('dbi:Mock:MySQL', '', ''); Or, by using the database name if using driver DSNs: DBI->connect('dbi:Mock:host=localhost;port=3306;database=MySQL', '', ''); The C in the DSN will be picked up and the MySQL specific attribute aliasing will be used. Right now there is only minimal support for MySQL and MariaDB: =over 4 =item MySQL Currently the C attribute for C<$dbh> and C<$sth> are aliased to the C<$dbh> attribute C. =item MariaDB Currently the C attribute for C<$dbh> and C<$sth> are aliased to the C<$dbh> attribute C. =back It is possible to add more aliases though, using the C function (see the source code for details) =head2 Database Driver Methods =over 4 =item B> This returns the value of C. =back In order to capture C, C, and C, C will create statements for them, as if you had issued them in the appropriate SQL command line program. They will go through the standard C-C cycle, meaning that any custom SQL parsers will be triggered and C will need to know about these statements. =over 4 =item B> This will create a statement with SQL of C and no parameters. =item B> This will create a statement with SQL of C and no parameters. =item B> This will create a statement with SQL of C and no parameters. =back =head2 Statement Handle Properties =over 4 =item B> Returns true if the handle is a C and has more records to fetch, false otherwise. (This is from the DBI, see the 'Active' docs under 'ATTRIBUTES COMMON TO ALL HANDLES'.) =item B> (Statement attribute C) Sets the state of the tracker C flag. =item B> (Statement attribute C) If set to C tells the tracker that the statement is finished. This resets the current record number to C<0> and clears out the array ref of returned records. =item B> (Statement attribute C) Returns true if the current record number is greater than the number of records set to return. =item B> Returns the number of fields set in the C parameter. =item B> Returns the number of records in the current result set. =item B> Returns the number of parameters set in the C parameter. =item B> Sets bound parameter C<$param_num> to C<$value>. Returns the arrayref of currently-set bound parameters. This corresponds to the C statement handle call. =item B> Pushes C<@params> onto the list of already-set bound parameters. =item B> Tells the tracker that the statement has been executed and resets the current record number to C<0>. =item B> If the statement has been depleted (all records returned) returns C; otherwise it gets the current record for returning, increments the current record number and returns the current record. =item B> Tries to give a decent depiction of the object state for use in debugging. =back =head1 DBD::Mock::StatementTrack::Iterator This object can be used to iterate through the current set of C objects in the history by fetching the C attribute from a database handle. This object is very simple and is meant to be a convenience to make writing long test script easier. Aside from the constructor (C) this object has the following methods. =over 4 =item B> Calling C will return the next C object in the history. If there are no more C objects available, then this method will return false. =item B> This will reset the internal pointer to the beginning of the statement history. =back =head1 DBD::Mock::Session The C object is an alternate means of specifying the SQL statements and result sets for C. The idea is that you can specify a complete 'session' of usage, which will be verified through C. Here is an example: my $session = DBD::Mock::Session->new('my_session' => ( { statement => "SELECT foo FROM bar", # as a string results => [[ 'foo' ], [ 'baz' ]] }, { statement => qr/UPDATE bar SET foo \= \'bar\'/, # as a reg-exp results => [[]] }, { statement => sub { # as a CODE ref my ($SQL, $state) = @_; return $SQL eq "SELECT foo FROM bar"; }, results => [[ 'foo' ], [ 'bar' ]] }, { # with bound parameters statement => "SELECT foo FROM bar WHERE baz = ? AND borg = ?", # check exact bound param value, # then check it against regexp bound_params => [ 10, qr/\d+/ ], results => [[ 'foo' ], [ 'baz' ]] } )); As you can see, a session is essentially made up a list of HASH references we call 'states'. Each state has a C and a set of C. If C finds a session in the C attribute, then it will pass the current C<$dbh> and SQL statement to that C. The SQL statement will be checked against the C field in the current state. If it passes, then the C of the current state will get fed to C through the C attribute. We then advance to the next state in the session, and wait for the next call through C. If at any time the SQL statement does not match the current state's C, or the session runs out of available states, an error will be raised (and propagated through the normal DBI error handling based on your values for C and C). As can be seen in the session element, bound parameters can also be supplied and tested. In this statement, the SQL is compared, then when the statement is executed, the bound parameters are also checked. The bound parameters must match in both number of parameters and the parameters themselves, or an error will be raised. As can also be seen in the example above, C fields can come in many forms. The simplest is a string, which will be compared using C against the currently running statement. The next is a reg-exp reference, this too will get compared against the currently running statement. The last option is a CODE ref, this is sort of a catch-all to allow for a wide range of SQL comparison approaches (including using modules like L or L for detailed functional comparisons). The first argument to the CODE ref will be the currently active SQL statement to compare against, the second argument is a reference to the current state HASH (in case you need to alter the results, or store extra information). The CODE is evaluated in boolean context and throws and exception if it is false. =over 4 =item B> A C<$session_name> can be optionally be specified, along with at least one C<@session_states>. If you don't specify a C<$session_name>, then a default one will be created for you. The C<@session_states> must all be HASH references as well, if this conditions fail, an exception will be thrown. =item B> This will check the C<$SQL> against the current state's C value, and if it passes will add the current state's C to the C<$dbh>. If for some reason the C value is bad, not of the prescribed type, an exception is thrown. See above for more details. =item B> If the C slot is available in the current state, this will check the C<$params> against the current state's C value. Both number of parameters and the parameters themselves must match, or an error will be raised. Parameters are compared using string comparison or, when a regular expression is supplied in the parameter position, matched against the regular expression. When a PostgreSQL database is mocked my $dbh = DBI->connect('dbi:Mock:PostgreSQL', ...); support for bound array parameters (a feature specific to L) is enabled. Array elements are compared using the comparison method above. Array elements which are themselves arrays are I traversed into. my $session = DBD::Mock::Session->new( 'my_session' => ( { statement => 'SELECT foo FROM bar WHERE baz = ANY(?)', bound_params => [ [ 'uvw', 'xyz' ] # bound array param ] } )); =item B> Calling this method will reset the state of the session object so that it can be reused. =back =head1 EXPERIMENTAL FUNCTIONALITY All functionality listed here is highly experimental and should be used with great caution (if at all). =over 4 =item Connection Callbacks This feature allows you to define callbacks that get executed when C<< DBI->connect >> is called. To set a series of callbacks you use the C function use DBD::Mock::dr; DBD::Mock::dr::set_connect_callbacks( sub { my ( $dbh, $dsn, $user, $password, $attributes ) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT foo FROM bar', results => [[ 'foo' ], [ 10 ]] }; } ); To set more than one callback to you can simply add extra callbacks to your call to C DBD::Mock::dr::set_connect_callbacks( sub { my ( $dbh, $dsn, $user, $password, $attributes ) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT foo FROM bar', results => [[ 'foo' ], [ 10 ]] }; }, sub { my ( $dbh, $dsn, $user, $password, $attributes ) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT foo FROM bar', results => [[ 'foo' ], [ 10 ]] }; } ); Or you can extend the existing set of callbacks with the C function DBD::Mock::dr::add_connect_callbacks( sub { ( my $dbh, $dsn, $user, $password, $attributes ) = @_; $dbh->{mock_add_resultset} = { sql => 'SELECT bar FROM foo', results => [[ 'bar' ], [ 50 ]] }; } ); =item table_info This feature adds support for DBI's C method ( I). To mock the table info for a search of the C database schema you would use the following: $dbh->{mock_add_table_info} = { cataloge => undef, schema => 'testSchema', table => undef, type => undef, table_info => [ [ 'TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS' ], [ undef, 'testSchema', 'foo', 'TABLE', undef ], [ undef, 'testSchema', 'bar', 'VIEW', undef ], ], }; The C, C, C and C parameters need to explicitly match what you expect table_info to be called with (note: C treats C and C<''> the same). Similar to the C, the C parameter's first entry is an arrayref of column names, and the rest are the values of the rows returned (one arrayref per row). If you need to cover listing schemas then you'd use: $dbh->{mock_add_table_info} = { schema => '%', table_info => [ [ 'TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS' ], [ undef, 'testSchema', undef, undef, undef ], [ undef, 'testSchema_2', undef, undef, undef ], ], } To clear the current mocked table info set the database handle's C attribute to C<1> $dbh->{mock_clear_table_info} = 1; =item Result Set Callbacks If you need your result sets to be more dynamic (e.g. if they need to return different results based upon bound parameters) then you can use a callback. $dbh->{mock_add_resultset} = { sql => 'SELECT a FROM b WHERE c = ?', callback => sub { my @bound_params = @_; my %result = ( fields => [ "a" ], rows => [[ 1] ] ); if ($bound_params[0] == 1) { $result{rows} = [ [32] ]; } elsif ($bound_params[0] == 2) { $result{rows} = [ [43] ]; } return %result; }, }; my $sth = $dbh->prepare('SELECT a FROM b WHERE c = ?'); my $rows = $sth->execute(1); my ($result) = $sth->fetchrow_array(); # $result will be 32 $rows = $sth->execute(2); ($result) = $sth->fetchrow_array(); # $result this time will be 43 $rows = $sth->execute(33); # $results this time will be 1 ($result) = $sth->fetchrow_array(); The callback needs to return a hash with a C key that is an array ref of arrays containing the values to return as the answer to the query. In addition a C key can also be returned with an array ref of field names. If a C key isn't present in the returned the hash then the fields will be taken from the C's C parameter. $dbh->{mock_add_resultset} = { sql => 'SELECT x FROM y WHERE z = ?', results => [ ["x"] ], callback => sub { my @bound_params = @_; my %result = ( rows => [[ 1] ] ); if ($bound_params[0] == 1) { $result{rows} = [ [32] ]; } elsif ($bound_params[0] == 2) { $result{rows} = [ [43] ]; } return %result; }, }; my $sth = $dbh->prepare('SELECT x FROM y WHERE z = ?'); my $rows = $sth->execute(1); my ($result) = $sth->fetchrow_array(); # $result will be 32 $rows = $sth->execute(2); ($result) = $sth->fetchrow_array(); # $result will be 43 $rows = $sth->execute(33); ($result) = $sth->fetchrow_array(); # $result will be 1 By default result sets which only define their field names in their callback return values will have a C property of C<0> until after the statement has actually been executed. This is to make sure that C stays compatible with previous versions. If you need the C property to be undef in this situation then set the C<$DBD::Mock::DefaultFieldsToUndef> flag to C<1>. If you're mocking an INSERT statement with a callback and you want to explicitly set the database's C value then you can use the C key in the result set. If you don't specify a C then the standard C logic for generating an value for the last inserted item will be followed. This will allow you to mock MySQL/MariaDB INSERT queries that use C logic to set the C. $dbh->{mock_add_resultset} = { sql => 'INSERT INTO y ( x ) VALUES ( ? ) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID( id )', callback => sub { my @bound_params = @_; my %result = ( fields => [], rows => [], last_insert_id => 99, ); return %result; }, }; =item Result Set Custom Attributes If you're mocking a database driver that has it's own custom attributes attached to its statement handles then you can use the result sets C and C options. The C option takes a hashref that maps statement handle attribute names to their values. The attributes are set at the point that the statement is prepared. $dbh->{mock_add_resultset} = { sql => 'SELECT foo FROM bar', prepare_attributes => { sqlite_unprepared_statements => ' ', }, results => [[ 'foo' ], [ 10 ]] }; The C option also takes a hashref that maps statement handle attribute names to their values, however these will only be set when the statement is executed. $dbh->{mock_add_resultset} = { sql => 'SELECT foo FROM bar', execute_attributes => { syb_result_type => 1, }, results => [[ 'foo' ], [ 10 ]] }; If an attribute is also present in the C option then the C version will take precedence up to the point the statement handle is executed, at which point the C version will take precedence. It is also possible to set C from a result set's callback by returning them under the C key in your callback's response. $dbh->{mock_add_resultset} = { sql => 'SELECT baz FROM qux', callback => sub { my @bound_params = @_; my %result = ( fields => [ 'baz'], rows => [], execute_attributes => { foo => 'bar' }, ); return %result; } }; If a result set has an C option and a callback that also returns an C key then the callback's C value will take precedence. =back =head1 BUGS =over =item Odd C<$dbh> attribute behavior When writing the test suite I encountered some odd behavior with some C<$dbh> attributes. I still need to get deeper into how DBD's work to understand what it is that is actually doing wrong. =back =head1 TO DO =over =item Make DBD specific handlers Each DBD has its own quirks and issues, it would be nice to be able to handle those issues with C in some way. I have an number of ideas already, but little time to sit down and really flesh them out. If you have any suggestions or thoughts, feel free to email me with them. =item Enhance the C object I would like to have the C object handle more of the C attributes. This would encapsulate much of the C behavior in one place, which would be a good thing. =back =head1 SEE ALSO L L, which provided a good starting point L, which provided the approach Test::MockObject article - L Perl Code Kata: Testing Databases - L =head1 ACKNOWLEDGEMENTS =over 4 =item Thanks to Ryan Gerry for his patch in RT #26604. =item Thanks to Marc Beyer for his patch in RT #16951. =item Thanks to Justin DeVuyst for the mock_connect_fail idea. =item Thanks to Thilo Planz for the code for C. =item Thanks to Shlomi Fish for help tracking down RT Bug #11515. =item Thanks to Collin Winter for the patch to fix the C, C and C methods. =item Thanks to Andrew McHarg Eamcharg@acm.orgE for C, C and C methods and tests. =item Thanks to Andrew W. Gibbs for the C patch and test. =item Thanks to Chas Owens for patch and test for the C, C, and C features. =item Thanks to Tomas Zemresfor the unit test in RT #71438. =item Thanks to Bernhard Graf for multiple patches fixing a range of issues and adding a new I feature to C. =item Thanks to Erik Huelsmann for testing the new result set custom attributes feature and also adding support for using arrayref's as bound parameters with PostgreSQL databases. =back =head1 COPYRIGHT Copyright (C) 2004 Chris Winters Echris@cwinters.comE Copyright (C) 2004-2007 Stevan Little Estevan@iinteractive.comE Copyright (C) 2007 Rob Kinyon Erob.kinyon@gmail.comE Copyright (C) 2011 Mariano Wahlmann Edichoso _at_ gmail.comE Copyright (C) 2019 Jason Cooper EJLCOOPER@cpan.orgE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 AUTHORS Chris Winters Echris@cwinters.comE Stevan Little Estevan@iinteractive.comE Rob Kinyon Erob.kinyon@gmail.comE Mariano Wahlmann Edichoso _at_ gmail.comE Jason Cooper EJLCOOPER@cpan.orgE =cut