Mojo-Pg-Che

 view release on metacpan or  search on metacpan

t/07-base-crud.t  view on Meta::CPAN

use Mojo::Base -strict;

BEGIN { $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll' }

use Test::More;

#~ plan skip_all => 'set TEST_ONLINE to enable this test' unless $ENV{TEST_ONLINE};
plan skip_all => 'set env TEST_PG="dbname=<...>/<pg_user>/<passwd>" to enable this test' unless $ENV{TEST_PG};

my ($dsn, $user, $pw) = split m|[/]|, $ENV{TEST_PG};

use Mojo::IOLoop;
use Mojo::Pg::Che;

# Isolate tests
#~ my $pg = Mojo::Pg::Che->new($ENV{TEST_ONLINE})->search_path(['mojo_crud_test']);
my $pg = Mojo::Pg::Che->connect($dsn, $user, $pw, {PrintWarn => 0,}, search_path=>['mojo_crud_test'])
  ->pg;#max_connections=>20
#~ is_deeply $pg->options, {}, 'right options';
$pg->db->query('drop schema if exists mojo_crud_test cascade');
$pg->db->query('create schema mojo_crud_test');

my $db = $pg->db;
$db->query(
  'create table if not exists crud_test (
     id   serial primary key,
     name text
   )'
);

# Create
$db->insert('crud_test', {name => 'foo'});
is_deeply $db->select('crud_test')->hashes->to_array,
  [{id => 1, name => 'foo'}], 'right structure';
is $db->insert('crud_test', {name => 'bar'}, {returning => 'id'})->hash->{id},
  2, 'right value';
is_deeply $db->select('crud_test')->hashes->to_array,
  [{id => 1, name => 'foo'}, {id => 2, name => 'bar'}], 'right structure';
$db->insert('crud_test', {id => 1, name => 'foo'}, {on_conflict => undef});
$db->insert(
  'crud_test',
  {id          => 2, name => 'bar'},
  {on_conflict => [id => {name => 'baz'}]}
);

# Read
is_deeply $db->select('crud_test')->hashes->to_array,
  [{id => 1, name => 'foo'}, {id => 2, name => 'baz'}], 'right structure';
is_deeply $db->select('crud_test', ['name'])->hashes->to_array,
  [{name => 'foo'}, {name => 'baz'}], 'right structure';
is_deeply $db->select('crud_test', ['name'], {name => 'foo'})->hashes->to_array,
  [{name => 'foo'}], 'right structure';
is_deeply $db->select('crud_test', ['name'], undef, {-desc => 'id'})
  ->hashes->to_array, [{name => 'baz'}, {name => 'foo'}], 'right structure';
is_deeply $db->select('crud_test', undef, undef, {offset => 1})
  ->hashes->to_array, [{id => 2, name => 'baz'}], 'right structure';
is_deeply $db->select('crud_test', undef, undef, {limit => 1})
  ->hashes->to_array, [{id => 1, name => 'foo'}], 'right structure';

# Non-blocking read
my $result;
my $delay = Mojo::IOLoop->delay(sub { $result = pop->hashes->to_array });
$db->select('crud_test', $delay->begin);
$delay->wait;
is_deeply $result, [{id => 1, name => 'foo'}, {id => 2, name => 'baz'}],
  'right structure';
$result = undef;
$delay  = Mojo::IOLoop->delay(sub { $result = pop->hashes->to_array });
$db->select('crud_test', undef, undef, {-desc => 'id'}, $delay->begin);
$delay->wait;



( run in 0.659 second using v1.01-cache-2.11-cpan-71847e10f99 )