| 1 |
# NAME |
| 2 |
|
| 3 |
DBD::Mock - Mock database driver for testing |
| 4 |
|
| 5 |
# SYNOPSIS |
| 6 |
|
| 7 |
use DBI; |
| 8 |
|
| 9 |
# connect to your as normal, using 'Mock' as your driver name |
| 10 |
my $dbh = DBI->connect( 'DBI:Mock:', '', '' ) |
| 11 |
|| die "Cannot create handle: $DBI::errstr\n"; |
| 12 |
|
| 13 |
# create a statement handle as normal and execute with parameters |
| 14 |
my $sth = $dbh->prepare( 'SELECT this, that FROM foo WHERE id = ?' ); |
| 15 |
$sth->execute( 15 ); |
| 16 |
|
| 17 |
# Now query the statement handle as to what has been done with it |
| 18 |
my $mock_params = $sth->{mock_params}; |
| 19 |
print "Used statement: ", $sth->{mock_statement}, "\n", |
| 20 |
"Bound parameters: ", join( ', ', @{ $mock_params } ), "\n"; |
| 21 |
|
| 22 |
# DESCRIPTION |
| 23 |
|
| 24 |
Testing with databases can be tricky. If you are developing a system married to |
| 25 |
a single database then you can make some assumptions about your environment and |
| 26 |
ask the user to provide relevant connection information. But if you need to |
| 27 |
test a framework that uses DBI, particularly a framework that uses different |
| 28 |
types of persistence schemes, then it may be more useful to simply verify what |
| 29 |
the framework is trying to do -- ensure the right SQL is generated and that the |
| 30 |
correct parameters are bound. `DBD::Mock` makes it easy to just modify your |
| 31 |
configuration (presumably held outside your code) and just use it instead of |
| 32 |
`DBD::Foo` (like [DBD::Pg](https://metacpan.org/pod/DBD%3A%3APg) or [DBD::mysql](https://metacpan.org/pod/DBD%3A%3Amysql)) in your framework. |
| 33 |
|
| 34 |
There is no distinct area where using this module makes sense. (Some people may |
| 35 |
successfully argue that this is a solution looking for a problem...) Indeed, if |
| 36 |
you can assume your users have something like [DBD::AnyData](https://metacpan.org/pod/DBD%3A%3AAnyData) or [DBD::SQLite](https://metacpan.org/pod/DBD%3A%3ASQLite) |
| 37 |
or if you do not mind creating a dependency on them then it makes far more sense |
| 38 |
to use these legitimate driver implementations and test your application in the |
| 39 |
real world -- at least as much of the real world as you can create in your |
| 40 |
tests... |
| 41 |
|
| 42 |
And if your database handle exists as a package variable or something else |
| 43 |
easily replaced at test-time then it may make more sense to use |
| 44 |
[Test::MockObject](https://metacpan.org/pod/Test%3A%3AMockObject) to create a fully dynamic handle. There is an excellent |
| 45 |
article by chromatic about using [Test::MockObject](https://metacpan.org/pod/Test%3A%3AMockObject) in this and other ways, |
| 46 |
strongly recommended. (See ["SEE ALSO"](#see-also) for a link) |
| 47 |
|
| 48 |
## How does it work? |
| 49 |
|
| 50 |
`DBD::Mock` comprises a set of classes used by DBI to implement a database |
| 51 |
driver. But instead of connecting to a datasource and manipulating data found |
| 52 |
there it tracks all the calls made to the database handle and any created |
| 53 |
statement handles. You can then inspect them to ensure what you wanted to |
| 54 |
happen actually happened. For instance, say you have a configuration file with |
| 55 |
your database connection information: |
| 56 |
|
| 57 |
[DBI] |
| 58 |
dsn = DBI:Pg:dbname=myapp |
| 59 |
user = foo |
| 60 |
password = bar |
| 61 |
|
| 62 |
And this file is read in at process startup and the handle stored for other |
| 63 |
procedures to use: |
| 64 |
|
| 65 |
package ObjectDirectory; |
| 66 |
|
| 67 |
my ( $DBH ); |
| 68 |
|
| 69 |
sub run_at_startup { |
| 70 |
my ( $class, $config ) = @_; |
| 71 |
$config ||= read_configuration( ... ); |
| 72 |
my $dsn = $config->{DBI}{dsn}; |
| 73 |
my $user = $config->{DBI}{user}; |
| 74 |
my $pass = $config->{DBI}{password}; |
| 75 |
$DBH = DBI->connect( $dsn, $user, $pass ) || die ...; |
| 76 |
} |
| 77 |
|
| 78 |
sub get_database_handle { |
| 79 |
return $DBH; |
| 80 |
} |
| 81 |
|
| 82 |
A procedure might use it like this (ignoring any error handling for the |
| 83 |
moment): |
| 84 |
|
| 85 |
package My::UserActions; |
| 86 |
|
| 87 |
sub fetch_user { |
| 88 |
my ( $class, $login ) = @_; |
| 89 |
my $dbh = ObjectDirectory->get_database_handle; |
| 90 |
my $sql = q{ |
| 91 |
SELECT login_name, first_name, last_name, creation_date, num_logins |
| 92 |
FROM users |
| 93 |
WHERE login_name = ? |
| 94 |
}; |
| 95 |
my $sth = $dbh->prepare( $sql ); |
| 96 |
$sth->execute( $login ); |
| 97 |
my $row = $sth->fetchrow_arrayref; |
| 98 |
return ( $row ) ? User->new( $row ) : undef; |
| 99 |
} |
| 100 |
|
| 101 |
So for the purposes of our tests we just want to ensure that: |
| 102 |
|
| 103 |
- 1. The right SQL is being executed |
| 104 |
- 2. The right parameters are bound |
| 105 |
|
| 106 |
Assume whether the SQL actually **works** or not is irrelevant for this test :-) |
| 107 |
|
| 108 |
To do that our test might look like: |
| 109 |
|
| 110 |
my $config = ObjectDirectory->read_configuration( ... ); |
| 111 |
$config->{DBI}{dsn} = 'DBI:Mock:'; |
| 112 |
ObjectDirectory->run_at_startup( $config ); |
| 113 |
|
| 114 |
my $login_name = 'foobar'; |
| 115 |
my $user = My::UserActions->fetch_user( $login_name ); |
| 116 |
|
| 117 |
# Get the handle from ObjectDirectory; |
| 118 |
# this is the same handle used in the |
| 119 |
# 'fetch_user()' procedure above |
| 120 |
my $dbh = ObjectDirectory->get_database_handle(); |
| 121 |
|
| 122 |
# Ask the database handle for the history |
| 123 |
# of all statements executed against it |
| 124 |
my $history = $dbh->{mock_all_history}; |
| 125 |
|
| 126 |
# Now query that history record to |
| 127 |
# see if our expectations match reality |
| 128 |
is(scalar(@{$history}), 1, 'Correct number of statements executed' ; |
| 129 |
|
| 130 |
my $login_st = $history->[0]; |
| 131 |
like($login_st->statement, |
| 132 |
qr/SELECT login_name.*FROM users WHERE login_name = ?/sm, |
| 133 |
'Correct statement generated' ); |
| 134 |
|
| 135 |
my $params = $login_st->bound_params; |
| 136 |
is(scalar(@{$params}), 1, 'Correct number of parameters bound'); |
| 137 |
is($params->[0], $login_name, 'Correct value for parameter 1' ); |
| 138 |
|
| 139 |
# Reset the handle for future operations |
| 140 |
$dbh->{mock_clear_history} = 1; |
| 141 |
|
| 142 |
The list of properties and what they return is listed below. But in an overall |
| 143 |
view: |
| 144 |
|
| 145 |
- A database handle contains the history of all statements created against it. |
| 146 |
Other properties set for the handle (e.g., `PrintError`, `RaiseError`) are |
| 147 |
left alone and can be queried as normal, but they do not affect anything. (A |
| 148 |
future feature may track the sequence/history of these assignments but if there |
| 149 |
is no demand it probably will not get implemented.) |
| 150 |
- A statement handle contains the statement it was prepared with plus all bound |
| 151 |
parameters or parameters passed via `execute()`. It can also contain |
| 152 |
predefined results for the statement handle to `fetch`, track how many fetches |
| 153 |
were called and what its current record is. |
| 154 |
|
| 155 |
## A Word of Warning |
| 156 |
|
| 157 |
This may be an incredibly naive implementation of a DBD. But it works for me... |
| 158 |
|
| 159 |
# DBD::Mock |
| 160 |
|
| 161 |
Since this is a normal DBI statement handle we need to expose our tracking |
| 162 |
information as properties (accessed like a hash) rather than methods. |
| 163 |
|
| 164 |
## Database Driver Properties |
| 165 |
|
| 166 |
- **`mock_connect_fail`** |
| 167 |
|
| 168 |
This is a boolean property which when set to true (`1`) will not allow DBI to |
| 169 |
connect. This can be used to simulate a DSN error or authentication failure. |
| 170 |
This can then be set back to false (`0`) to resume normal DBI operations. Here |
| 171 |
is an example of how this works: |
| 172 |
|
| 173 |
# install the DBD::Mock driver |
| 174 |
my $drh = DBI->install_driver('Mock'); |
| 175 |
|
| 176 |
$drh->{mock_connect_fail} = 1; |
| 177 |
|
| 178 |
# this connection will fail |
| 179 |
my $dbh = DBI->connect('dbi:Mock:', '', '') || die "Cannot connect"; |
| 180 |
|
| 181 |
# this connection will throw an exception |
| 182 |
my $dbh = DBI->connect('dbi:Mock:', '', '', { RaiseError => 1 }); |
| 183 |
|
| 184 |
$drh->{mock_connect_fail} = 0; |
| 185 |
|
| 186 |
# this will work now ... |
| 187 |
my $dbh = DBI->connect(...); |
| 188 |
|
| 189 |
This feature is conceptually different from the `mock_can_connect` attribute |
| 190 |
of the `$dbh` in that it has a driver-wide scope, where `mock_can_connect` |
| 191 |
is handle-wide scope. It also only prevents the initial connection, any `$dbh` |
| 192 |
handles created prior to setting `mock_connect_fail` to true (`1`) will still |
| 193 |
go on working just fine. |
| 194 |
|
| 195 |
- **`mock_data_sources`** |
| 196 |
|
| 197 |
This is an ARRAY reference which holds fake data sources which are returned by |
| 198 |
the Driver and Database Handle's `data_source()` method. |
| 199 |
|
| 200 |
- **`mock_add_data_sources`** |
| 201 |
|
| 202 |
This takes a string and adds it to the `mock_data_sources` attribute. |
| 203 |
|
| 204 |
## Database Handle Properties |
| 205 |
|
| 206 |
- **`mock_all_history`** |
| 207 |
|
| 208 |
Returns an array reference with all history (a.k.a. |
| 209 |
`DBD::Mock::StatementTrack`) objects created against the database handle in |
| 210 |
the order they were created. Each history object can then report information |
| 211 |
about the SQL statement used to create it, the bound parameters, etc.. |
| 212 |
|
| 213 |
- **`mock_all_history_iterator`** |
| 214 |
|
| 215 |
Returns a `DBD::Mock::StatementTrack::Iterator` object which will iterate |
| 216 |
through the current set of `DBD::Mock::StatementTrack` object in the history. |
| 217 |
See the ["DBD::Mock::StatementTrack::Iterator"](#dbd-mock-statementtrack-iterator) documentation below for more |
| 218 |
information. |
| 219 |
|
| 220 |
- **`mock_clear_history`** |
| 221 |
|
| 222 |
If set to a true value all previous statement history operations will be |
| 223 |
erased. This **includes** the history of currently open handles, so if you do |
| 224 |
something like: |
| 225 |
|
| 226 |
my $dbh = get_handle( ... ); |
| 227 |
my $sth = $dbh->prepare( ... ); |
| 228 |
$dbh->{mock_clear_history} = 1; |
| 229 |
$sth->execute( 'Foo' ); |
| 230 |
|
| 231 |
You will have no way to learn from the database handle that the statement |
| 232 |
parameter 'Foo' was bound. |
| 233 |
|
| 234 |
This is useful mainly to ensure you can isolate the statement histories from |
| 235 |
each other. A typical sequence will look like: |
| 236 |
|
| 237 |
set handle to framework |
| 238 |
perform operations |
| 239 |
analyze mock database handle |
| 240 |
reset mock database handle history |
| 241 |
perform more operations |
| 242 |
analyze mock database handle |
| 243 |
reset mock database handle history |
| 244 |
... |
| 245 |
|
| 246 |
- **`mock_can_connect`** |
| 247 |
|
| 248 |
This statement allows you to simulate a downed database connection. This is |
| 249 |
useful in testing how your application/tests will perform in the face of some |
| 250 |
kind of catastrophic event such as a network outage or database server failure. |
| 251 |
It is a simple boolean value which defaults to on, and can be set like this: |
| 252 |
|
| 253 |
# turn the database off |
| 254 |
$dbh->{mock_can_connect} = 0; |
| 255 |
|
| 256 |
# turn it back on again |
| 257 |
$dbh->{mock_can_connect} = 1; |
| 258 |
|
| 259 |
The statement handle checks this value as well, so something like this |
| 260 |
will fail in the expected way: |
| 261 |
|
| 262 |
$dbh = DBI->connect( 'DBI:Mock:', '', '' ); |
| 263 |
$dbh->{mock_can_connect} = 0; |
| 264 |
|
| 265 |
# blows up! |
| 266 |
my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) }); |
| 267 |
if ( $@ ) { |
| 268 |
# Here, $DBI::errstr = 'No connection present' |
| 269 |
} |
| 270 |
|
| 271 |
Turning off the database after a statement prepare will fail on the statement |
| 272 |
`execute()`, which is hopefully what you would expect: |
| 273 |
|
| 274 |
$dbh = DBI->connect( 'DBI:Mock:', '', '' ); |
| 275 |
|
| 276 |
# ok! |
| 277 |
my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) }); |
| 278 |
$dbh->{mock_can_connect} = 0; |
| 279 |
|
| 280 |
# blows up! |
| 281 |
$sth->execute; |
| 282 |
|
| 283 |
Similarly: |
| 284 |
|
| 285 |
$dbh = DBI->connect( 'DBI:Mock:', '', '' ); |
| 286 |
|
| 287 |
# ok! |
| 288 |
my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) }); |
| 289 |
|
| 290 |
# ok! |
| 291 |
$sth->execute; |
| 292 |
|
| 293 |
$dbh->{mock_can_connect} = 0; |
| 294 |
|
| 295 |
# blows up! |
| 296 |
my $row = $sth->fetchrow_arrayref; |
| 297 |
|
| 298 |
Note: The handle attribute `Active` and the handle method `ping` will behave |
| 299 |
according to the value of `mock_can_connect`. So if `mock_can_connect` were |
| 300 |
to be set to `0` (or off), then both `Active` and `ping` would return false |
| 301 |
values (or `0`). |
| 302 |
|
| 303 |
- **`mock_add_resultset( \@resultset | \%resultset_and_options )`** |
| 304 |
|
| 305 |
This stocks the database handle with a record set, allowing you to seed data |
| 306 |
for your application to see if it works properly. Each recordset is a simple |
| 307 |
arrayref of arrays with the first arrayref being the field names used. Every |
| 308 |
time a statement handle is created it asks the database handle if it has any |
| 309 |
resultsets available and if so uses it. |
| 310 |
|
| 311 |
Here is a sample usage, partially from the test suite: |
| 312 |
|
| 313 |
my @user_results = ( |
| 314 |
[ 'login', 'first_name', 'last_name' ], |
| 315 |
[ 'cwinters', 'Chris', 'Winters' ], |
| 316 |
[ 'bflay', 'Bobby', 'Flay' ], |
| 317 |
[ 'alincoln', 'Abe', 'Lincoln' ], |
| 318 |
); |
| 319 |
my @generic_results = ( |
| 320 |
[ 'foo', 'bar' ], |
| 321 |
[ 'this_one', 'that_one' ], |
| 322 |
[ 'this_two', 'that_two' ], |
| 323 |
); |
| 324 |
|
| 325 |
my $dbh = DBI->connect( 'DBI:Mock:', '', '' ); |
| 326 |
$dbh->{mock_add_resultset} = \@user_results; # add first resultset |
| 327 |
$dbh->{mock_add_resultset} = \@generic_results; # add second resultset |
| 328 |
my ( $sth ); |
| 329 |
eval { |
| 330 |
$sth = $dbh->prepare( 'SELECT login, first_name, last_name FROM foo' ); |
| 331 |
$sth->execute(); |
| 332 |
}; |
| 333 |
|
| 334 |
# this will fetch rows from the first resultset... |
| 335 |
my $row1 = $sth->fetchrow_arrayref; |
| 336 |
my $user1 = User->new( login => $row->[0], |
| 337 |
first => $row->[1], |
| 338 |
last => $row->[2] ); |
| 339 |
is( $user1->full_name, 'Chris Winters' ); |
| 340 |
|
| 341 |
my $row2 = $sth->fetchrow_arrayref; |
| 342 |
my $user2 = User->new( login => $row->[0], |
| 343 |
first => $row->[1], |
| 344 |
last => $row->[2] ); |
| 345 |
is( $user2->full_name, 'Bobby Flay' ); |
| 346 |
... |
| 347 |
|
| 348 |
my $sth_generic = $dbh->prepare( 'SELECT foo, bar FROM baz' ); |
| 349 |
$sth_generic->execute; |
| 350 |
|
| 351 |
# this will fetch rows from the second resultset... |
| 352 |
my $row = $sth->fetchrow_arrayref; |
| 353 |
|
| 354 |
It is possible to assign a hashref where the resultset must be given as |
| 355 |
value for the `results` key: |
| 356 |
|
| 357 |
$dbh->{mock_add_resultset} = { |
| 358 |
results => [ |
| 359 |
[ 'foo', 'bar' ], |
| 360 |
[ 'this_one', 'that_one' ], |
| 361 |
[ 'this_two', 'that_two' ], |
| 362 |
], |
| 363 |
}; |
| 364 |
|
| 365 |
The reason for the hashref form is that you can add options as described |
| 366 |
in the following. |
| 367 |
|
| 368 |
You can associate a resultset with a particular SQL statement instead of |
| 369 |
adding them in the order they will be fetched: |
| 370 |
|
| 371 |
$dbh->{mock_add_resultset} = { |
| 372 |
sql => 'SELECT foo, bar FROM baz', |
| 373 |
results => [ |
| 374 |
[ 'foo', 'bar' ], |
| 375 |
[ 'this_one', 'that_one' ], |
| 376 |
[ 'this_two', 'that_two' ], |
| 377 |
], |
| 378 |
}; |
| 379 |
|
| 380 |
This will return the given results when the statement |
| 381 |
'`SELECT foo, bar FROM baz`' is prepared/executed. Note that they will be |
| 382 |
returned **every time** the statement is prepared/executed, not just the first. |
| 383 |
It should also be noted that if you want, for some reason, to change the result |
| 384 |
set bound to a particular SQL statement, all you need to do is add the result |
| 385 |
set again with the same SQL statement and `DBD::Mock` will overwrite it. |
| 386 |
|
| 387 |
If the `sql` parameter is a regular expression reference then the results will |
| 388 |
be returned for any SQL statements that matches it: |
| 389 |
|
| 390 |
$dbh->{mock_add_resultset} = { |
| 391 |
sql => qr/^SELECT foo FROM/i, |
| 392 |
results => [ |
| 393 |
[ 'foo' ], |
| 394 |
[ 'this_one' ], |
| 395 |
], |
| 396 |
}; |
| 397 |
|
| 398 |
If an SQL statement matches both a specified SQL statement result set and a |
| 399 |
regular expression result set then the specified SQL statement takes precedence. |
| 400 |
If two regular expression result sets match then the first one added takes |
| 401 |
precedence: |
| 402 |
|
| 403 |
# Set up our first regex matching result set |
| 404 |
$dbh->{mock_add_resultset} = { |
| 405 |
sql => qr/^SELECT foo/, |
| 406 |
results => [ [ 'foo' ], [ 200 ] ], |
| 407 |
}; |
| 408 |
|
| 409 |
# Set up our second regex matching result set |
| 410 |
# Note - This results set would never be used as the one above will match |
| 411 |
# and thus take precedence |
| 412 |
$dbh->{mock_add_resultset} = { |
| 413 |
sql => qr/^SELECT foo FROM/, |
| 414 |
results => [ [ 'foo' ], [ 300 ] ], |
| 415 |
}; |
| 416 |
|
| 417 |
# Set up our first statically defined result set |
| 418 |
# This result set will take precedence over the regex matching ones above |
| 419 |
$dbh->{mock_add_resultset} = { |
| 420 |
sql => 'SELECT foo FROM bar', |
| 421 |
results => [[ 'foo' ], [ 50 ]] |
| 422 |
}; |
| 423 |
|
| 424 |
# This query will be served by the first regex matching result set |
| 425 |
my $sth = $dbh->prepare('SELECT foo FROM oof'); |
| 426 |
$sth->execute() |
| 427 |
|
| 428 |
my ($result) = $sth->fetchrow_array(); |
| 429 |
is( $result, 200 ); |
| 430 |
|
| 431 |
# This quere will be served by the statically defined result set |
| 432 |
$sth = $dbh->prepare('SELECT foo FROM bar'); |
| 433 |
$sth->execute(); |
| 434 |
|
| 435 |
my ($result2) = $sth->fetchrow_array(); |
| 436 |
is( $result2, 50 ); |
| 437 |
|
| 438 |
It should also be noted that the `rows` method will return the number of |
| 439 |
records stocked in the result set. So if your code/application makes use of the |
| 440 |
`$sth->rows` method for things like `UPDATE` and `DELETE` calls you |
| 441 |
should stock the result set like so: |
| 442 |
|
| 443 |
$dbh->{mock_add_resultset} = { |
| 444 |
sql => 'UPDATE foo SET baz = 1, bar = 2', |
| 445 |
# this will appear to have updated 3 rows |
| 446 |
results => [[ 'rows' ], [], [], []], |
| 447 |
}; |
| 448 |
|
| 449 |
# or ... |
| 450 |
|
| 451 |
$dbh->{mock_add_resultset} = { |
| 452 |
sql => 'DELETE FROM foo WHERE bar = 2', |
| 453 |
# this will appear to have deleted 1 row |
| 454 |
results => [[ 'rows' ], []], |
| 455 |
}; |
| 456 |
|
| 457 |
Now I admit this is not the most elegant way to go about this, but it works for |
| 458 |
me for now, and until I can come up with a better method, or someone sends me a |
| 459 |
patch ;) it will do for now. |
| 460 |
|
| 461 |
If you want a given statement to fail, you will have to use the hashref method |
| 462 |
and add a `failure` key. That key must be handed an arrayref with the error |
| 463 |
number and error string, in that order. |
| 464 |
|
| 465 |
$dbh->{mock_add_resultset} = { |
| 466 |
sql => 'SELECT foo FROM bar', |
| 467 |
results => DBD::Mock->NULL_RESULTSET, |
| 468 |
failure => [ 5, 'Ooops!' ], |
| 469 |
}; |
| 470 |
|
| 471 |
Without the `sql` attribute the next statement will fail in any case: |
| 472 |
|
| 473 |
$dbh->{mock_add_resultset} = { |
| 474 |
results => DBD::Mock->NULL_RESULTSET, |
| 475 |
failure => [ 5, 'Ooops!' ], |
| 476 |
}; |
| 477 |
|
| 478 |
- **`mock_get_info`** |
| 479 |
|
| 480 |
This attribute can be used to set up values for `get_info()`. It takes a |
| 481 |
hashref of attribute\_name/value pairs. See [DBI](https://metacpan.org/pod/DBI) for more information on the |
| 482 |
information types and their meaning. |
| 483 |
|
| 484 |
- **`mock_session`** |
| 485 |
|
| 486 |
This attribute can be used to set a current `DBD::Mock::Session` object. For |
| 487 |
more information on this, see the ["DBD::Mock::Session"](#dbd-mock-session) docs below. This |
| 488 |
attribute can also be used to remove the current session from the `$dbh` |
| 489 |
simply by setting it to `undef`. |
| 490 |
|
| 491 |
- **`mock_last_insert_id`** |
| 492 |
|
| 493 |
This attribute is incremented each time an `INSERT` statement is passed to |
| 494 |
`prepare` on a per-handle basis. It's starting value can be set with the |
| 495 |
`mock_start_insert_id` attribute (see below). |
| 496 |
|
| 497 |
$dbh->{mock_start_insert_id} = 10; |
| 498 |
|
| 499 |
my $sth = $dbh->prepare('INSERT INTO Foo (foo, bar) VALUES(?, ?)'); |
| 500 |
|
| 501 |
$sth->execute(1, 2); |
| 502 |
# $dbh->{mock_last_insert_id} == 10 |
| 503 |
|
| 504 |
$sth->execute(3, 4); |
| 505 |
# $dbh->{mock_last_insert_id} == 11 |
| 506 |
|
| 507 |
For more examples, please refer to the test file |
| 508 |
`t/025_mock_last_insert_id.t`. |
| 509 |
|
| 510 |
To access `last_insert_id` using driver specific attributes like |
| 511 |
`mysql_insertid` and `mariadb_insertid` then you can use |
| 512 |
["Attribute Aliasing"](#attribute-aliasing). |
| 513 |
|
| 514 |
- **`mock_start_insert_id`** |
| 515 |
|
| 516 |
This attribute can be used to set a start value for the `mock_last_insert_id` |
| 517 |
attribute. It can also be used to effectively reset the `mock_last_insert_id` |
| 518 |
attribute as well. |
| 519 |
|
| 520 |
This attribute also can be used with an ARRAY ref parameter, it's behavior is |
| 521 |
slightly different in that instead of incrementing the value for every |
| 522 |
`prepare` it will only increment for each `execute`. This allows it to be |
| 523 |
used over multiple `execute` calls in a single `$sth`. It's usage looks like |
| 524 |
this: |
| 525 |
|
| 526 |
$dbh->{mock_start_insert_id} = [ 'Foo', 10 ]; |
| 527 |
$dbh->{mock_start_insert_id} = [ 'Baz', 20 ]; |
| 528 |
|
| 529 |
my $sth1 = $dbh->prepare('INSERT INTO Foo (foo, bar) VALUES(?, ?)'); |
| 530 |
|
| 531 |
my $sth2 = $dbh->prepare('INSERT INTO Baz (baz, buz) VALUES(?, ?)'); |
| 532 |
|
| 533 |
$sth1->execute(1, 2); |
| 534 |
# $dbh->{mock_last_insert_id} == 10 |
| 535 |
|
| 536 |
$sth2->execute(3, 4); |
| 537 |
# $dbh->{mock_last_insert_id} == 20 |
| 538 |
|
| 539 |
Note that `DBD::Mock`'s matching of table names in `INSERT` statements is |
| 540 |
fairly simple, so if your table names are quoted in the insert statement |
| 541 |
(`INSERT INTO "Foo"`) then you need to quote the name for |
| 542 |
`mock_start_insert_id`: |
| 543 |
|
| 544 |
$dbh->{mock_start_insert_id} = [ q{"Foo"}, 10 ]; |
| 545 |
|
| 546 |
- **`mock_add_parser`** |
| 547 |
|
| 548 |
DBI provides some simple parsing capabilities for `SELECT` statements to |
| 549 |
ensure that placeholders are bound properly. And typically you may simply want |
| 550 |
to check after the fact that a statement is syntactically correct, or at least |
| 551 |
what you expect. |
| 552 |
|
| 553 |
But other times you may want to parse the statement as it is prepared rather |
| 554 |
than after the fact. There is a hook in this mock database driver for you to |
| 555 |
provide your own parsing routine or object. |
| 556 |
|
| 557 |
The syntax is simple: |
| 558 |
|
| 559 |
$dbh->{mock_add_parser} = sub { |
| 560 |
my ( $sql ) = @_; |
| 561 |
unless ( $sql =~ /some regex/ ) { |
| 562 |
die "does not contain secret fieldname"; |
| 563 |
} |
| 564 |
}; |
| 565 |
|
| 566 |
You can also add more than one for a handle. They will be called in order, and |
| 567 |
the first one to fail will halt the parsing process: |
| 568 |
|
| 569 |
$dbh->{mock_add_parser} = \&parse_update_sql; |
| 570 |
$dbh->{mock_add-parser} = \&parse_insert_sql; |
| 571 |
|
| 572 |
Depending on the `PrintError` and `RaiseError` settings in the database |
| 573 |
handle any parsing errors encountered will issue a `warn` or `die`. No matter |
| 574 |
what the statement handle will be `undef`. |
| 575 |
|
| 576 |
Instead of providing a subroutine reference you can use an object. The only |
| 577 |
requirement is that it implements the method `parse()` and takes a SQL |
| 578 |
statement as the only argument. So you should be able to do something like the |
| 579 |
following (untested): |
| 580 |
|
| 581 |
my $parser = SQL::Parser->new( 'mysql', { RaiseError => 1 } ); |
| 582 |
$dbh->{mock_add_parser} = $parser; |
| 583 |
|
| 584 |
- **`mock_data_sources`** & **`mock_add_data_sources`** |
| 585 |
|
| 586 |
These properties will dispatch to the Driver's properties of the same name. |
| 587 |
|
| 588 |
## Attribute Aliasing |
| 589 |
|
| 590 |
Basically this feature allows you to alias attributes to other attributes. So |
| 591 |
for instance, you can alias a commonly expected attribute like |
| 592 |
`mysql_insertid` to something `DBD::Mock` already has like |
| 593 |
`mock_last_insert_id`. While you can also just set `mysql_insertid` yourself, |
| 594 |
this functionality allows it to take advantage of things like the |
| 595 |
autoincrementing of the `mock_last_insert_id` attribute. |
| 596 |
|
| 597 |
The functionality is off by default so as to not cause any issues with |
| 598 |
backwards compatibility, but can easily be turned on and off like this: |
| 599 |
|
| 600 |
# turn it on |
| 601 |
$DBD::Mock::AttributeAliasing++; |
| 602 |
|
| 603 |
# turn it off |
| 604 |
$DBD::Mock::AttributeAliasing = 0; |
| 605 |
|
| 606 |
Once this is turned on, you will need to choose a database specific attribute |
| 607 |
aliasing table like so: |
| 608 |
|
| 609 |
DBI->connect('dbi:Mock:MySQL', '', ''); |
| 610 |
|
| 611 |
Or, by using the database name if using driver DSNs: |
| 612 |
|
| 613 |
DBI->connect('dbi:Mock:host=localhost;port=3306;database=MySQL', '', ''); |
| 614 |
|
| 615 |
The `MySQL` in the DSN will be picked up and the MySQL specific attribute |
| 616 |
aliasing will be used. |
| 617 |
|
| 618 |
Right now there is only minimal support for MySQL and MariaDB: |
| 619 |
|
| 620 |
- MySQL |
| 621 |
|
| 622 |
Currently the `mysql_insertid` attribute for `$dbh` and `$sth` are aliased |
| 623 |
to the `$dbh` attribute `mock_last_insert_id`. |
| 624 |
|
| 625 |
- MariaDB |
| 626 |
|
| 627 |
Currently the `mariadb_insertid` attribute for `$dbh` and `$sth` are aliased |
| 628 |
to the `$dbh` attribute `mock_last_insert_id`. |
| 629 |
|
| 630 |
It is possible to add more aliases though, using the |
| 631 |
`DBD::Mock:_set_mock_attribute_aliases` function (see the source code for |
| 632 |
details) |
| 633 |
|
| 634 |
## Database Driver Methods |
| 635 |
|
| 636 |
- **`last_insert_id`** |
| 637 |
|
| 638 |
This returns the value of `mock_last_insert_id`. |
| 639 |
|
| 640 |
In order to capture `begin_work()`, `commit()`, and `rollback()`, |
| 641 |
`DBD::Mock` will create statements for them, as if you had issued them in the |
| 642 |
appropriate SQL command line program. They will go through the standard |
| 643 |
`prepare()`-`execute()` cycle, meaning that any custom SQL parsers will be |
| 644 |
triggered and `DBD::Mock::Session` will need to know about these statements. |
| 645 |
|
| 646 |
- **`begin_work`** |
| 647 |
|
| 648 |
This will create a statement with SQL of `BEGIN WORK` and no parameters. |
| 649 |
|
| 650 |
- **`commit`** |
| 651 |
|
| 652 |
This will create a statement with SQL of `COMMIT` and no parameters. |
| 653 |
|
| 654 |
- **`rollback`** |
| 655 |
|
| 656 |
This will create a statement with SQL of `ROLLBACK` and no parameters. |
| 657 |
|
| 658 |
## Statement Handle Properties |
| 659 |
|
| 660 |
- **`Active`** |
| 661 |
|
| 662 |
Returns true if the handle is a `SELECT` and has more records to fetch, false |
| 663 |
otherwise. (From the DBI.) |
| 664 |
|
| 665 |
- **`mock_statement`** |
| 666 |
|
| 667 |
The SQL statement this statement handle was `prepare`d with. So if the handle |
| 668 |
was created with: |
| 669 |
|
| 670 |
my $sth = $dbh->prepare( 'SELECT * FROM foo' ); |
| 671 |
|
| 672 |
This would return: |
| 673 |
|
| 674 |
SELECT * FROM foo |
| 675 |
|
| 676 |
The original statement is unmodified so if you are checking against it in tests |
| 677 |
you may want to use a regex rather than a straight equality check. (However if |
| 678 |
you use a phrasebook to store your SQL externally you are a step ahead...) |
| 679 |
|
| 680 |
- **`mock_fields`** |
| 681 |
|
| 682 |
Fields used by the statement. As said elsewhere we do no analysis or parsing to |
| 683 |
find these, you need to define them beforehand. That said, you do not actually |
| 684 |
need this very often. |
| 685 |
|
| 686 |
Note that this returns the same thing as the normal statement property |
| 687 |
`FIELD`. |
| 688 |
|
| 689 |
- **`mock_params`** |
| 690 |
|
| 691 |
Returns an arrayref of parameters bound to this statement in the order |
| 692 |
specified by the bind type. For instance, if you created and stocked a handle |
| 693 |
with: |
| 694 |
|
| 695 |
my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' ); |
| 696 |
$sth->bind_param( 2, 'yes' ); |
| 697 |
$sth->bind_param( 1, 7783 ); |
| 698 |
|
| 699 |
This would return: |
| 700 |
|
| 701 |
[ 7738, 'yes' ] |
| 702 |
|
| 703 |
The same result will occur if you pass the parameters via `execute()` instead: |
| 704 |
|
| 705 |
my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' ); |
| 706 |
$sth->execute( 7783, 'yes' ); |
| 707 |
|
| 708 |
The same using named parameters |
| 709 |
|
| 710 |
my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = :id AND is_active = :active' ); |
| 711 |
$sth->bind_param( ':id' => 7783 ); |
| 712 |
$sth->bind_param( ':active' => 'yes' ); |
| 713 |
|
| 714 |
- **`mock_param_attrs`** |
| 715 |
|
| 716 |
Returns an arrayref of any attributes (parameter type) defined for bound |
| 717 |
parameters (note: you rarely need to define attributes for bound parameters). |
| 718 |
Where an attribute/type hasn't been that slot in the returned arrayref will be |
| 719 |
`undef`. e.g. for: |
| 720 |
|
| 721 |
my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' ); |
| 722 |
$sth->bind_param( 2, 'yes' ); |
| 723 |
$sth->bind_param( 1 7783, SQL_INTEGER ); |
| 724 |
|
| 725 |
This would return: |
| 726 |
|
| 727 |
[ SQL_INTEGER, undef ] |
| 728 |
|
| 729 |
Passing parameters via `execute()` will always populate the array with |
| 730 |
`undef`, so for: |
| 731 |
|
| 732 |
$sth->execute( 7783, 'yes' ); |
| 733 |
|
| 734 |
This would return: |
| 735 |
|
| 736 |
[ undef, undef ] |
| 737 |
|
| 738 |
- **`mock_execution_history`** |
| 739 |
|
| 740 |
Returns an arrayref where each entry contains the details for an execution of |
| 741 |
the prepared statement. e.g. after: |
| 742 |
|
| 743 |
my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' ); |
| 744 |
$sth->bind_param( 2, 'yes' ); |
| 745 |
$sth->bind_param( 1 7783, SQL_INTEGER ); |
| 746 |
$sth->execute(); |
| 747 |
|
| 748 |
$sth->execute( 1023, 'no' ); |
| 749 |
|
| 750 |
Then `$sth->{mock_execution_history}` would be: |
| 751 |
|
| 752 |
[ |
| 753 |
{ |
| 754 |
params => [ 7783, 'yes' ], |
| 755 |
attrs => [ SQL_INTEGER, undef ], |
| 756 |
}, { |
| 757 |
params => [ 1023, 'no' ], |
| 758 |
attrs => [ undef, undef ], |
| 759 |
} |
| 760 |
] |
| 761 |
|
| 762 |
- **`mock_records`** |
| 763 |
|
| 764 |
An arrayref of arrayrefs representing the records the mock statement was |
| 765 |
stocked with. |
| 766 |
|
| 767 |
- **`mock_num_records`** |
| 768 |
|
| 769 |
Number of records the mock statement was stocked with; if never stocked it is |
| 770 |
still `0`. (Some weirdos might expect undef...) |
| 771 |
|
| 772 |
- **`mock_num_rows`** |
| 773 |
|
| 774 |
This returns the same value as _mock\_num\_records_. And is what is returned by |
| 775 |
the `rows` method of the statement handle. |
| 776 |
|
| 777 |
- **`mock_current_record_num`** |
| 778 |
|
| 779 |
Current record the statement is on; returns `0` in the instances when you have |
| 780 |
not yet called `execute()` and if you have not yet called a `fetch` method |
| 781 |
after the execute. |
| 782 |
|
| 783 |
- **`mock_is_executed`** |
| 784 |
|
| 785 |
Whether `execute()` has been called against the statement handle. Returns |
| 786 |
'yes' if so, 'no' if not. |
| 787 |
|
| 788 |
- **`mock_is_finished`** |
| 789 |
|
| 790 |
Whether `finish()` has been called against the statement handle. Returns 'yes' |
| 791 |
if so, 'no' if not. |
| 792 |
|
| 793 |
- **`mock_is_depleted`** |
| 794 |
|
| 795 |
Returns 'yes' if all the records in the recordset have been returned. If no |
| 796 |
`fetch()` was executed against the statement, or If no return data was set |
| 797 |
this will return 'no'. |
| 798 |
|
| 799 |
- **`mock_my_history`** |
| 800 |
|
| 801 |
Returns a `DBD::Mock::StatementTrack` object which tracks the actions |
| 802 |
performed by this statement handle. Most of the actions are separately |
| 803 |
available from the properties listed above, so you should never need this. |
| 804 |
|
| 805 |
# DBD::Mock::Pool |
| 806 |
|
| 807 |
This module can be used to emulate [Apache::DBI](https://metacpan.org/pod/Apache%3A%3ADBI) style DBI connection pooling. |
| 808 |
Just as with `Apache::DBI`, you must enable `DBD::Mock::Pool` before loading |
| 809 |
DBI. |
| 810 |
|
| 811 |
use DBD::Mock qw(Pool); |
| 812 |
# followed by ... |
| 813 |
use DBI; |
| 814 |
|
| 815 |
While this may not seem to make a lot of sense in a single-process testing |
| 816 |
scenario, it can be useful when testing code which assumes a multi-process |
| 817 |
`Apache::DBI` pooled environment. |
| 818 |
|
| 819 |
# DBD::Mock::StatementTrack |
| 820 |
|
| 821 |
Under the hood this module does most of the work with a |
| 822 |
`DBD::Mock::StatementTrack` object. This is most useful when you are reviewing |
| 823 |
multiple statements at a time, otherwise you might want to use the `mock_*` |
| 824 |
statement handle attributes instead. |
| 825 |
|
| 826 |
- **`new( %params )`** |
| 827 |
|
| 828 |
Takes the following parameters: |
| 829 |
|
| 830 |
- **`return_data`**: Arrayref of return data records |
| 831 |
- **`fields`**: Arrayref of field names |
| 832 |
- **`bound_params`**: Arrayref of bound parameters |
| 833 |
- **`bound_param_attrs`**: Arrayref of bound parameter attributes |
| 834 |
|
| 835 |
- **`statement`** (Statement attribute `mock_statement`) |
| 836 |
|
| 837 |
Gets/sets the SQL statement used. |
| 838 |
|
| 839 |
- **`fields`** (Statement attribute `mock_fields`) |
| 840 |
|
| 841 |
Gets/sets the fields to use for this statement. |
| 842 |
|
| 843 |
- **`bound_params`** (Statement attribute `mock_params`) |
| 844 |
|
| 845 |
Gets/set the bound parameters to use for this statement. |
| 846 |
|
| 847 |
- **`return_data`** (Statement attribute `mock_records`) |
| 848 |
|
| 849 |
Gets/sets the data to return when asked (that is, when someone calls `fetch` |
| 850 |
on the statement handle). |
| 851 |
|
| 852 |
- **`current_record_num`** (Statement attribute `mock_current_record_num`) |
| 853 |
|
| 854 |
Gets/sets the current record number. |
| 855 |
|
| 856 |
- **`is_active()`** (Statement attribute `Active`) |
| 857 |
|
| 858 |
Returns true if the statement is a `SELECT` and has more records to fetch, |
| 859 |
false otherwise. (This is from the DBI, see the 'Active' docs under 'ATTRIBUTES |
| 860 |
COMMON TO ALL HANDLES'.) |
| 861 |
|
| 862 |
- **`is_executed( $yes_or_no )`** (Statement attribute `mock_is_executed`) |
| 863 |
|
| 864 |
Sets the state of the tracker `executed` flag. |
| 865 |
|
| 866 |
- **`is_finished( $yes_or_no )`** (Statement attribute `mock_is_finished`) |
| 867 |
|
| 868 |
If set to `yes` tells the tracker that the statement is finished. This resets |
| 869 |
the current record number to `0` and clears out the array ref of returned |
| 870 |
records. |
| 871 |
|
| 872 |
- **`is_depleted()`** (Statement attribute `mock_is_depleted`) |
| 873 |
|
| 874 |
Returns true if the current record number is greater than the number of records |
| 875 |
set to return. |
| 876 |
|
| 877 |
- **`num_fields`** |
| 878 |
|
| 879 |
Returns the number of fields set in the `fields` parameter. |
| 880 |
|
| 881 |
- **`num_rows`** |
| 882 |
|
| 883 |
Returns the number of records in the current result set. |
| 884 |
|
| 885 |
- **`num_params`** |
| 886 |
|
| 887 |
Returns the number of parameters set in the `bound_params` parameter. |
| 888 |
|
| 889 |
- **`bound_param( $param_num, $value )`** |
| 890 |
|
| 891 |
Sets bound parameter `$param_num` to `$value`. Returns the arrayref of |
| 892 |
currently-set bound parameters. This corresponds to the `bind_param` statement |
| 893 |
handle call. |
| 894 |
|
| 895 |
- **`bound_param_trailing( @params )`** |
| 896 |
|
| 897 |
Pushes `@params` onto the list of already-set bound parameters. |
| 898 |
|
| 899 |
- **`mark_executed()`** |
| 900 |
|
| 901 |
Tells the tracker that the statement has been executed and resets the current |
| 902 |
record number to `0`. |
| 903 |
|
| 904 |
- **`next_record()`** |
| 905 |
|
| 906 |
If the statement has been depleted (all records returned) returns `undef`; |
| 907 |
otherwise it gets the current record for returning, increments the current |
| 908 |
record number and returns the current record. |
| 909 |
|
| 910 |
- **`to_string()`** |
| 911 |
|
| 912 |
Tries to give a decent depiction of the object state for use in debugging. |
| 913 |
|
| 914 |
# DBD::Mock::StatementTrack::Iterator |
| 915 |
|
| 916 |
This object can be used to iterate through the current set of |
| 917 |
`DBD::Mock::StatementTrack` objects in the history by fetching the |
| 918 |
`mock_all_history_iterator` attribute from a database handle. This object is |
| 919 |
very simple and is meant to be a convenience to make writing long test script |
| 920 |
easier. Aside from the constructor (`new`) this object has the following |
| 921 |
methods. |
| 922 |
|
| 923 |
- **`next()`** |
| 924 |
|
| 925 |
Calling `next` will return the next `DBD::Mock::StatementTrack` object in the |
| 926 |
history. If there are no more `DBD::Mock::StatementTrack` objects available, |
| 927 |
then this method will return false. |
| 928 |
|
| 929 |
- **`reset()`** |
| 930 |
|
| 931 |
This will reset the internal pointer to the beginning of the statement history. |
| 932 |
|
| 933 |
# DBD::Mock::Session |
| 934 |
|
| 935 |
The `DBD::Mock::Session` object is an alternate means of specifying the SQL |
| 936 |
statements and result sets for `DBD::Mock`. The idea is that you can specify a |
| 937 |
complete 'session' of usage, which will be verified through `DBD::Mock`. Here |
| 938 |
is an example: |
| 939 |
|
| 940 |
my $session = DBD::Mock::Session->new('my_session' => ( |
| 941 |
{ |
| 942 |
statement => "SELECT foo FROM bar", # as a string |
| 943 |
results => [[ 'foo' ], [ 'baz' ]] |
| 944 |
}, |
| 945 |
{ |
| 946 |
statement => qr/UPDATE bar SET foo \= \'bar\'/, # as a reg-exp |
| 947 |
results => [[]] |
| 948 |
}, |
| 949 |
{ |
| 950 |
statement => sub { # as a CODE ref |
| 951 |
my ($SQL, $state) = @_; |
| 952 |
return $SQL eq "SELECT foo FROM bar"; |
| 953 |
}, |
| 954 |
results => [[ 'foo' ], [ 'bar' ]] |
| 955 |
}, |
| 956 |
{ |
| 957 |
# with bound parameters |
| 958 |
statement => "SELECT foo FROM bar WHERE baz = ? AND borg = ?", |
| 959 |
# check exact bound param value, |
| 960 |
# then check it against regexp |
| 961 |
bound_params => [ 10, qr/\d+/ ], |
| 962 |
results => [[ 'foo' ], [ 'baz' ]] |
| 963 |
} |
| 964 |
)); |
| 965 |
|
| 966 |
As you can see, a session is essentially made up a list of HASH references we |
| 967 |
call 'states'. Each state has a `statement` and a set of `results`. If |
| 968 |
`DBD::Mock` finds a session in the `mock_session` attribute, then it will |
| 969 |
pass the current `$dbh` and SQL statement to that `DBD::Mock::Session`. The |
| 970 |
SQL statement will be checked against the `statement` field in the current |
| 971 |
state. If it passes, then the `results` of the current state will get fed to |
| 972 |
`DBD::Mock` through the `mock_add_resultset` attribute. We then advance to |
| 973 |
the next state in the session, and wait for the next call through `DBD::Mock`. |
| 974 |
If at any time the SQL statement does not match the current state's |
| 975 |
`statement`, or the session runs out of available states, an error will be |
| 976 |
raised (and propagated through the normal DBI error handling based on your |
| 977 |
values for `RaiseError` and `PrintError`). |
| 978 |
|
| 979 |
As can be seen in the session element, bound parameters can also be supplied |
| 980 |
and tested. In this statement, the SQL is compared, then when the statement is |
| 981 |
executed, the bound parameters are also checked. The bound parameters must |
| 982 |
match in both number of parameters and the parameters themselves, or an error |
| 983 |
will be raised. |
| 984 |
|
| 985 |
As can also be seen in the example above, `statement` fields can come in many |
| 986 |
forms. The simplest is a string, which will be compared using `eq` against the |
| 987 |
currently running statement. The next is a reg-exp reference, this too will get |
| 988 |
compared against the currently running statement. The last option is a CODE |
| 989 |
ref, this is sort of a catch-all to allow for a wide range of SQL comparison |
| 990 |
approaches (including using modules like [SQL::Statement](https://metacpan.org/pod/SQL%3A%3AStatement) or [SQL::Parser](https://metacpan.org/pod/SQL%3A%3AParser) |
| 991 |
for detailed functional comparisons). The first argument to the CODE ref will |
| 992 |
be the currently active SQL statement to compare against, the second argument |
| 993 |
is a reference to the current state HASH (in case you need to alter the |
| 994 |
results, or store extra information). The CODE is evaluated in boolean context |
| 995 |
and throws and exception if it is false. |
| 996 |
|
| 997 |
- **`new ($session_name, @session_states)`** |
| 998 |
|
| 999 |
A `$session_name` can be optionally be specified, along with at least one |
| 1000 |
`@session_states`. If you don't specify a `$session_name`, then a default one |
| 1001 |
will be created for you. The `@session_states` must all be HASH references as |
| 1002 |
well, if this conditions fail, an exception will be thrown. |
| 1003 |
|
| 1004 |
- **`verify_statement ($dbh, $SQL)`** |
| 1005 |
|
| 1006 |
This will check the `$SQL` against the current state's `statement` value, and |
| 1007 |
if it passes will add the current state's `results` to the `$dbh`. If for |
| 1008 |
some reason the `statement` value is bad, not of the prescribed type, an |
| 1009 |
exception is thrown. See above for more details. |
| 1010 |
|
| 1011 |
- **`verify_bound_params ($dbh, $params)`** |
| 1012 |
|
| 1013 |
If the `bound_params` slot is available in the current state, this will check |
| 1014 |
the `$params` against the current state's `bound_params` value. Both number |
| 1015 |
of parameters and the parameters themselves must match, or an error will be |
| 1016 |
raised. |
| 1017 |
|
| 1018 |
Parameters are compared using string comparison or, when a regular expression |
| 1019 |
is supplied in the parameter position, matched against the regular expression. |
| 1020 |
|
| 1021 |
When a PostgreSQL database is mocked |
| 1022 |
|
| 1023 |
my $dbh = DBI->connect('dbi:Mock:PostgreSQL', ...); |
| 1024 |
|
| 1025 |
support for bound array parameters (a feature specific to [DBD::Pg](https://metacpan.org/pod/DBD%3A%3APg)) is |
| 1026 |
enabled. Array elements are compared using the comparison method above. Array |
| 1027 |
elements which are themselves arrays are _not_ traversed into. |
| 1028 |
|
| 1029 |
my $session = DBD::Mock::Session->new( 'my_session' => ( |
| 1030 |
{ |
| 1031 |
statement => 'SELECT foo FROM bar WHERE baz = ANY(?)', |
| 1032 |
bound_params => [ |
| 1033 |
[ 'uvw', 'xyz' ] # bound array param |
| 1034 |
] |
| 1035 |
} |
| 1036 |
)); |
| 1037 |
|
| 1038 |
- **`reset`** |
| 1039 |
|
| 1040 |
Calling this method will reset the state of the session object so that it can |
| 1041 |
be reused. |
| 1042 |
|
| 1043 |
# EXPERIMENTAL FUNCTIONALITY |
| 1044 |
|
| 1045 |
All functionality listed here is highly experimental and should be used with |
| 1046 |
great caution (if at all). |
| 1047 |
|
| 1048 |
- Connection Callbacks |
| 1049 |
|
| 1050 |
This feature allows you to define callbacks that get executed when |
| 1051 |
`DBI->connect` is called. |
| 1052 |
|
| 1053 |
To set a series of callbacks you use the |
| 1054 |
`DBD::Mock::dr::set_connect_callbacks` function |
| 1055 |
|
| 1056 |
use DBD::Mock::dr; |
| 1057 |
|
| 1058 |
DBD::Mock::dr::set_connect_callbacks( sub { |
| 1059 |
my ( $dbh, $dsn, $user, $password, $attributes ) = @_; |
| 1060 |
|
| 1061 |
$dbh->{mock_add_resultset} = { |
| 1062 |
sql => 'SELECT foo FROM bar', |
| 1063 |
results => [[ 'foo' ], [ 10 ]] |
| 1064 |
}; |
| 1065 |
} ); |
| 1066 |
|
| 1067 |
To set more than one callback to you can simply add extra callbacks to your |
| 1068 |
call to `DBD::Mock::dr::set_connect_callbacks` |
| 1069 |
|
| 1070 |
DBD::Mock::dr::set_connect_callbacks( |
| 1071 |
sub { |
| 1072 |
my ( $dbh, $dsn, $user, $password, $attributes ) = @_; |
| 1073 |
|
| 1074 |
$dbh->{mock_add_resultset} = { |
| 1075 |
sql => 'SELECT foo FROM bar', |
| 1076 |
results => [[ 'foo' ], [ 10 ]] |
| 1077 |
}; |
| 1078 |
}, |
| 1079 |
|
| 1080 |
sub { |
| 1081 |
my ( $dbh, $dsn, $user, $password, $attributes ) = @_; |
| 1082 |
|
| 1083 |
$dbh->{mock_add_resultset} = { |
| 1084 |
sql => 'SELECT foo FROM bar', |
| 1085 |
results => [[ 'foo' ], [ 10 ]] |
| 1086 |
}; |
| 1087 |
} |
| 1088 |
); |
| 1089 |
|
| 1090 |
Or you can extend the existing set of callbacks with the |
| 1091 |
`DBD::Mock::dr::add_connect_callbacks` function |
| 1092 |
|
| 1093 |
DBD::Mock::dr::add_connect_callbacks( sub { |
| 1094 |
( my $dbh, $dsn, $user, $password, $attributes ) = @_; |
| 1095 |
|
| 1096 |
$dbh->{mock_add_resultset} = { |
| 1097 |
sql => 'SELECT bar FROM foo', |
| 1098 |
results => [[ 'bar' ], [ 50 ]] |
| 1099 |
}; |
| 1100 |
} ); |
| 1101 |
|
| 1102 |
- table\_info |
| 1103 |
|
| 1104 |
This feature adds support for DBI's `table_info` method ( |
| 1105 |
_Note this functionality is unstable when used with DBI version 1.634 and below_). |
| 1106 |
|
| 1107 |
To mock the table info for a search of the `testSchema` database schema you |
| 1108 |
would use the following: |
| 1109 |
|
| 1110 |
$dbh->{mock_add_table_info} = { |
| 1111 |
cataloge => undef, |
| 1112 |
schema => 'testSchema', |
| 1113 |
table => undef, |
| 1114 |
type => undef, |
| 1115 |
table_info => [ |
| 1116 |
[ 'TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS' ], |
| 1117 |
[ undef, 'testSchema', 'foo', 'TABLE', undef ], |
| 1118 |
[ undef, 'testSchema', 'bar', 'VIEW', undef ], |
| 1119 |
], |
| 1120 |
}; |
| 1121 |
|
| 1122 |
The `cataloge`, `schema`, `table` and `type` parameters need to explicitly |
| 1123 |
match what you expect table\_info to be called with (note: `table_info` treats |
| 1124 |
`undef` and `''` the same). |
| 1125 |
|
| 1126 |
Similar to the `mock_results_sets`, the `table_info` parameter's first entry |
| 1127 |
is an arrayref of column names, and the rest are the values of the rows |
| 1128 |
returned (one arrayref per row). |
| 1129 |
|
| 1130 |
If you need to cover listing schemas then you'd use: |
| 1131 |
|
| 1132 |
$dbh->{mock_add_table_info} = { |
| 1133 |
schema => '%', |
| 1134 |
table_info => [ |
| 1135 |
[ 'TABLE_CAT', 'TABLE_SCHEM', 'TABLE_NAME', 'TABLE_TYPE', 'REMARKS' ], |
| 1136 |
[ undef, 'testSchema', undef, undef, undef ], |
| 1137 |
[ undef, 'testSchema_2', undef, undef, undef ], |
| 1138 |
], |
| 1139 |
} |
| 1140 |
|
| 1141 |
To clear the current mocked table info set the database handle's |
| 1142 |
`mock_clear_table_info` attribute to `1` |
| 1143 |
|
| 1144 |
$dbh->{mock_clear_table_info} = 1; |
| 1145 |
|
| 1146 |
- Result Set Callbacks |
| 1147 |
|
| 1148 |
If you need your result sets to be more dynamic (e.g. if they need to return |
| 1149 |
different results based upon bound parameters) then you can use a callback. |
| 1150 |
|
| 1151 |
$dbh->{mock_add_resultset} = { |
| 1152 |
sql => 'SELECT a FROM b WHERE c = ?', |
| 1153 |
callback => sub { |
| 1154 |
my @bound_params = @_; |
| 1155 |
|
| 1156 |
my %result = ( |
| 1157 |
fields => [ "a" ], |
| 1158 |
rows => [[ 1] ] |
| 1159 |
); |
| 1160 |
|
| 1161 |
if ($bound_params[0] == 1) { |
| 1162 |
$result{rows} = [ [32] ]; |
| 1163 |
} elsif ($bound_params[0] == 2) { |
| 1164 |
$result{rows} = [ [43] ]; |
| 1165 |
} |
| 1166 |
|
| 1167 |
return %result; |
| 1168 |
}, |
| 1169 |
}; |
| 1170 |
|
| 1171 |
my $sth = $dbh->prepare('SELECT a FROM b WHERE c = ?'); |
| 1172 |
|
| 1173 |
my $rows = $sth->execute(1); |
| 1174 |
my ($result) = $sth->fetchrow_array(); # $result will be 32 |
| 1175 |
|
| 1176 |
$rows = $sth->execute(2); |
| 1177 |
($result) = $sth->fetchrow_array(); # $result this time will be 43 |
| 1178 |
|
| 1179 |
$rows = $sth->execute(33); # $results this time will be 1 |
| 1180 |
|
| 1181 |
($result) = $sth->fetchrow_array(); |
| 1182 |
|
| 1183 |
The callback needs to return a hash with a `rows` key that is an array ref of |
| 1184 |
arrays containing the values to return as the answer to the query. In addition |
| 1185 |
a `fields` key can also be returned with an array ref of field names. If a |
| 1186 |
`fields` key isn't present in the returned the hash then the fields will be |
| 1187 |
taken from the `mock_add_resultset`'s `results` parameter. |
| 1188 |
|
| 1189 |
$dbh->{mock_add_resultset} = { |
| 1190 |
sql => 'SELECT x FROM y WHERE z = ?', |
| 1191 |
results => [ ["x"] ], |
| 1192 |
callback => sub { |
| 1193 |
my @bound_params = @_; |
| 1194 |
|
| 1195 |
my %result = ( rows => [[ 1] ] ); |
| 1196 |
|
| 1197 |
if ($bound_params[0] == 1) { |
| 1198 |
$result{rows} = [ [32] ]; |
| 1199 |
} elsif ($bound_params[0] == 2) { |
| 1200 |
$result{rows} = [ [43] ]; |
| 1201 |
} |
| 1202 |
|
| 1203 |
return %result; |
| 1204 |
}, |
| 1205 |
}; |
| 1206 |
|
| 1207 |
my $sth = $dbh->prepare('SELECT x FROM y WHERE z = ?'); |
| 1208 |
|
| 1209 |
my $rows = $sth->execute(1); |
| 1210 |
my ($result) = $sth->fetchrow_array(); # $result will be 32 |
| 1211 |
|
| 1212 |
$rows = $sth->execute(2); |
| 1213 |
($result) = $sth->fetchrow_array(); # $result will be 43 |
| 1214 |
|
| 1215 |
$rows = $sth->execute(33); |
| 1216 |
($result) = $sth->fetchrow_array(); # $result will be 1 |
| 1217 |
|
| 1218 |
By default result sets which only define their field names in their callback |
| 1219 |
return values will have a `NUM_OF_FIELDS` property of `0` until after the |
| 1220 |
statement has actually been executed. This is to make sure that `DBD::Mock` |
| 1221 |
stays compatible with previous versions. If you need the `NUM_OF_FIELDS` |
| 1222 |
property to be undef in this situation then set the |
| 1223 |
`$DBD::Mock::DefaultFieldsToUndef` flag to `1`. |
| 1224 |
|
| 1225 |
If you're mocking an INSERT statement with a callback and you want to |
| 1226 |
explicitly set the database's `last_insert_id` value then you can use the |
| 1227 |
`last_insert_id` key in the result set. If you don't specify a |
| 1228 |
`last_insert_id` then the standard `DBD::Mock` logic for generating an value |
| 1229 |
for the last inserted item will be followed. This will allow you to mock |
| 1230 |
MySQL/MariaDB INSERT queries that use `ON DUPLICATE KEY UPDATE` logic to set |
| 1231 |
the `last_insert_id`. |
| 1232 |
|
| 1233 |
$dbh->{mock_add_resultset} = { |
| 1234 |
sql => 'INSERT INTO y ( x ) VALUES ( ? ) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID( id )', |
| 1235 |
callback => sub { |
| 1236 |
my @bound_params = @_; |
| 1237 |
|
| 1238 |
my %result = ( |
| 1239 |
fields => [], |
| 1240 |
rows => [], |
| 1241 |
last_insert_id => 99, |
| 1242 |
); |
| 1243 |
|
| 1244 |
return %result; |
| 1245 |
}, |
| 1246 |
}; |
| 1247 |
|
| 1248 |
- Result Set Custom Attributes |
| 1249 |
|
| 1250 |
If you're mocking a database driver that has it's own custom attributes |
| 1251 |
attached to its statement handles then you can use the result sets |
| 1252 |
`prepare_attributes` and `execute_attributes` options. |
| 1253 |
|
| 1254 |
The `prepare_attributes` option takes a hashref that maps statement handle |
| 1255 |
attribute names to their values. The attributes are set at the point that |
| 1256 |
the statement is prepared. |
| 1257 |
|
| 1258 |
$dbh->{mock_add_resultset} = { |
| 1259 |
sql => 'SELECT foo FROM bar', |
| 1260 |
prepare_attributes => { |
| 1261 |
sqlite_unprepared_statements => ' ', |
| 1262 |
}, |
| 1263 |
results => [[ 'foo' ], [ 10 ]] |
| 1264 |
}; |
| 1265 |
|
| 1266 |
The `execute_attributes` option also takes a hashref that maps statement |
| 1267 |
handle attribute names to their values, however these will only be set when the |
| 1268 |
statement is executed. |
| 1269 |
|
| 1270 |
$dbh->{mock_add_resultset} = { |
| 1271 |
sql => 'SELECT foo FROM bar', |
| 1272 |
execute_attributes => { |
| 1273 |
syb_result_type => 1, |
| 1274 |
}, |
| 1275 |
results => [[ 'foo' ], [ 10 ]] |
| 1276 |
}; |
| 1277 |
|
| 1278 |
If an attribute is also present in the `prepare_attributes` option then the |
| 1279 |
`prepare_attributes` version will take precedence up to the point the |
| 1280 |
statement handle is executed, at which point the `execute_attributes` version |
| 1281 |
will take precedence. |
| 1282 |
|
| 1283 |
It is also possible to set `execute_attributes` from a result set's callback |
| 1284 |
by returning them under the `execute_attributes` key in your callback's |
| 1285 |
response. |
| 1286 |
|
| 1287 |
$dbh->{mock_add_resultset} = { |
| 1288 |
sql => 'SELECT baz FROM qux', |
| 1289 |
callback => sub { |
| 1290 |
my @bound_params = @_; |
| 1291 |
|
| 1292 |
my %result = ( |
| 1293 |
fields => [ 'baz'], |
| 1294 |
rows => [], |
| 1295 |
execute_attributes => { |
| 1296 |
foo => 'bar' |
| 1297 |
}, |
| 1298 |
); |
| 1299 |
|
| 1300 |
return %result; |
| 1301 |
} |
| 1302 |
}; |
| 1303 |
|
| 1304 |
If a result set has an `execute_attributes` option and a callback that also |
| 1305 |
returns an `execute_attributes` key then the callback's `execute_attributes` |
| 1306 |
value will take precedence. |
| 1307 |
|
| 1308 |
# BUGS |
| 1309 |
|
| 1310 |
- Odd `$dbh` attribute behavior |
| 1311 |
|
| 1312 |
When writing the test suite I encountered some odd behavior with some `$dbh` |
| 1313 |
attributes. I still need to get deeper into how DBD's work to understand what |
| 1314 |
it is that is actually doing wrong. |
| 1315 |
|
| 1316 |
# TO DO |
| 1317 |
|
| 1318 |
- Make DBD specific handlers |
| 1319 |
|
| 1320 |
Each DBD has its own quirks and issues, it would be nice to be able to handle |
| 1321 |
those issues with `DBD::Mock` in some way. I have an number of ideas already, |
| 1322 |
but little time to sit down and really flesh them out. If you have any |
| 1323 |
suggestions or thoughts, feel free to email me with them. |
| 1324 |
|
| 1325 |
- Enhance the `DBD::Mock::StatementTrack` object |
| 1326 |
|
| 1327 |
I would like to have the `DBD::Mock::StatementTrack` object handle more of the |
| 1328 |
`mock_*` attributes. This would encapsulate much of the `mock_*` behavior in |
| 1329 |
one place, which would be a good thing. |
| 1330 |
|
| 1331 |
# SEE ALSO |
| 1332 |
|
| 1333 |
[DBI](https://metacpan.org/pod/DBI) |
| 1334 |
|
| 1335 |
[DBD::NullP](https://metacpan.org/pod/DBD%3A%3ANullP), which provided a good starting point |
| 1336 |
|
| 1337 |
[Test::MockObject](https://metacpan.org/pod/Test%3A%3AMockObject), which provided the approach |
| 1338 |
|
| 1339 |
Test::MockObject article - [http://www.perl.com/pub/a/2002/07/10/tmo.html](http://www.perl.com/pub/a/2002/07/10/tmo.html) |
| 1340 |
|
| 1341 |
Perl Code Kata: Testing Databases - [http://www.perl.com/pub/a/2005/02/10/database\_kata.html](http://www.perl.com/pub/a/2005/02/10/database_kata.html) |
| 1342 |
|
| 1343 |
# ACKNOWLEDGEMENTS |
| 1344 |
|
| 1345 |
- Thanks to Ryan Gerry for his patch in RT #26604. |
| 1346 |
- Thanks to Marc Beyer for his patch in RT #16951. |
| 1347 |
- Thanks to Justin DeVuyst for the mock\_connect\_fail idea. |
| 1348 |
- Thanks to Thilo Planz for the code for `bind_param_inout`. |
| 1349 |
- Thanks to Shlomi Fish for help tracking down RT Bug #11515. |
| 1350 |
- Thanks to Collin Winter for the patch to fix the `begin_work()`, |
| 1351 |
`commit()` and `rollback()` methods. |
| 1352 |
- Thanks to Andrew McHarg <[email protected]> for |
| 1353 |
`fetchall_hashref()`, `fetchrow_hashref()` and `selectcol_arrayref()` |
| 1354 |
methods and tests. |
| 1355 |
- Thanks to Andrew W. Gibbs for the `mock_last_insert_ids` patch and test. |
| 1356 |
- Thanks to Chas Owens for patch and test for the `mock_can_prepare`, |
| 1357 |
`mock_can_execute`, and `mock_can_fetch` features. |
| 1358 |
- Thanks to Tomas Zemresfor the unit test in RT #71438. |
| 1359 |
- Thanks to Bernhard Graf for multiple patches fixing a range of issues |
| 1360 |
and adding a new _One Shot Failure_ feature to `mock_add_resultset`. |
| 1361 |
- Thanks to Erik Huelsmann for testing the new result set custom attributes |
| 1362 |
feature and also adding support for using arrayref's as bound parameters with |
| 1363 |
PostgreSQL databases. |
| 1364 |
|
| 1365 |
# COPYRIGHT |
| 1366 |
|
| 1367 |
Copyright (C) 2004 Chris Winters <[email protected]> |
| 1368 |
|
| 1369 |
Copyright (C) 2004-2007 Stevan Little <[email protected]> |
| 1370 |
|
| 1371 |
Copyright (C) 2007 Rob Kinyon <[email protected]> |
| 1372 |
|
| 1373 |
Copyright (C) 2011 Mariano Wahlmann <dichoso \_at\_ gmail.com> |
| 1374 |
|
| 1375 |
Copyright (C) 2019 Jason Cooper <[email protected]> |
| 1376 |
|
| 1377 |
This library is free software; you can redistribute it and/or modify |
| 1378 |
it under the same terms as Perl itself. |
| 1379 |
|
| 1380 |
# AUTHORS |
| 1381 |
|
| 1382 |
Chris Winters <[email protected]> |
| 1383 |
|
| 1384 |
Stevan Little <[email protected]> |
| 1385 |
|
| 1386 |
Rob Kinyon <[email protected]> |
| 1387 |
|
| 1388 |
Mariano Wahlmann <dichoso \_at\_ gmail.com> |
| 1389 |
|
| 1390 |
Jason Cooper <[email protected]> |