Trog-SQLite.t 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use strict;
  2. use warnings;
  3. use Test::More;
  4. use Test::MockModule qw{strict};
  5. use Test::Deep;
  6. use Test::Fatal qw{exception};
  7. use FindBin;
  8. use lib "$FindBin::Bin/../lib";
  9. require_ok('Trog::SQLite') or BAIL_OUT("Can't find SUT");
  10. subtest 'dbh' => sub {
  11. my $readmock = Test::MockModule->new('File::Slurper');
  12. $readmock->redefine( 'read_text', sub { "SELECT me FROM candidates" } );
  13. my $dbimock = Test::MockModule->new("DBI");
  14. $dbimock->redefine( 'connect', sub { bless( {}, 'TrogDBD' ) } );
  15. my $works = 0;
  16. no warnings qw{redefine once};
  17. local *TrogDBD::do = sub { $works };
  18. local *TrogDBD::errstr = sub { 'bogus' };
  19. like( exception { Trog::SQLite::dbh( 'bogus', 'bogus' ) }, qr/ensure/i, "Failure to enforce schema throws" );
  20. $works = 1;
  21. # Otherwise it works
  22. isa_ok( Trog::SQLite::dbh( 'bogus', 'bogus' ), 'TrogDBD' );
  23. unlink 'bogus';
  24. };
  25. subtest bulk_insert => sub {
  26. like( exception { Trog::SQLite::bulk_insert( {}, 'bogus', [qw{a b c}], 'PROCASTINATE' ) }, qr/unsupported/i, "insert OR keyword consistency enforced" );
  27. like( exception { Trog::SQLite::bulk_insert( {}, 'bogus', [] ) }, qr/nonempty/, "keys must be provided" );
  28. like( exception { Trog::SQLite::bulk_insert( {}, 'bogus', [qw{a b c}], 'IGNORE', qw{jello} ) }, qr/multiple of/i, "sufficient values must be provided" );
  29. my $smt;
  30. my $dbh = bless( {}, 'TrogDBH' );
  31. no warnings qw{redefine once};
  32. local *TrogDBH::prepare = sub { $smt .= $_[1]; return bless( {}, 'TrogSMT' ) };
  33. local *TrogSMT::execute = sub { };
  34. is( exception { Trog::SQLite::bulk_insert( $dbh, 'bogus', [qw{moo cows}], 'IGNORE', qw{a b c d} ) }, undef, "can do bulk insert" );
  35. is( $smt, "INSERT OR IGNORE INTO bogus (moo,cows) VALUES (?,?),(?,?)", "Expected query prepared" );
  36. # Million insert
  37. $smt = '';
  38. my $keys = [ ("a") x 10 ];
  39. my @values = ("b") x ( 10**6 );
  40. Trog::SQLite::bulk_insert( $dbh, 'bogus', $keys, 'IGNORE', @values );
  41. my $expected = "INSERT OR IGNORE INTO bogus (a,a,a,a,a,a,a,a,a,a) VALUES (?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?),(?,?,?,?,?,?,?,?,?,?)INSERT OR IGNORE INTO bogus (a,a,a,a,a,a,a,a,a,a) VALUES (?,?,?,?,?,?,?,?,?,?)";
  42. is( $smt, $expected, "As expected, only two statements are necessary to be prepared, no matter how many rows to insert." );
  43. };
  44. done_testing;