Thanks Brian!

I'm familiar with C. My goal with digging into DBI was to programmatically
cause a SQL error in a test case. I needed somehow to create a wrapper
around do (or execute) in which I'd examine the Statement and "die"
accordingly. This would allow me to validate database logic that rolled
back a transaction. The code I am testing is existing code and isn't
modulure. My thinking was to create an extension of an existing DBD module
(DBD::mysql) by having my extension module load first and insert "hooks" to
wrap the needed function: The below code works when $dbh->prepare and
$sth->execute are called in Perl code, but $dbh->do calls don't seem to
follow the same code path (XS stuff makes it act different). The code I'm
writing the test against has lots of INSERTs into tables using do, and it
is there that I'd like to generate the exception.

File DBD/mysql.pm (in a local directory to the test):

BEGIN {
       # fiddle with INC so correct module is loaded
        my $path = shift(@INC);
        push(@INC, $path);

        # lie to Perl so it will load the real DBD::mysql
        delete $INC{"DBD/mysql.pm"};
}

# put INC back to normal
INIT {
        my $path = pop(@INC);
        unshift(@INC, $path);
}

use DBD::mysql; # pulls in module from system dirs

use strict;

package DBD::mysql::st;

# hook into method by manipulating symbol table
my $orig_execute = \&execute;
*execute = \&my_execute;

sub my_execute {
    my($sth, @bind_values) = @_;

    print "execute: $sth->{'Statement'}\n";

    return $orig_execute->(@_);
}

I'm resorting to having the production code crash when an environment
variable is set and having the test set that variable and validating the
results. :(




On Wed, Apr 25, 2018 at 2:06 PM Fennell, Brian <fenne...@radial.com> wrote:

> For quick and dirty debugging in C I usually put together something like
> this : open file in append mode, write to file, close file.  (this way is
> the code crashes you still have something useful in your debug log).
>
> Using C’s getenv allows the debug logging to be turned on/off with an
> environment variable at run time (no fancy config file parsing needed).
>
>
>
> Here are some examples if you are new to C
>
>
>
> https://www.tutorialspoint.com/c_standard_library/c_function_fprintf.htm
>
> https://www.tutorialspoint.com/c_standard_library/c_function_getenv.htm
>
> http://rosettacode.org/wiki/Category:C
>
>
>
> And in the “more than you wanted to know” department (including xs
> tutorial, perl internals, and how to use gdb on perl)
>
>
>
> http://perldoc.perl.org/perlhacktips.html
>
> http://perldoc.perl.org/index-internals.html
>
-- 
Jeff Macdonald
Ayer, MA

Reply via email to