cleanup last insert id handling
[dbsrgits/DBIx-Data-Store-old.git] / t / 01basic_collection.t
1 use Test::More;
2 use DBIx::Data::Store;
3 use DBIx::Data::Store::CRUD;
4 use DBIx::Data::Collection::Set;
5 use DBI;
6 use Scalar::Util qw(refaddr);
7
8 use Devel::Dwarn;
9
10 use strict;
11 use warnings FATAL => 'all';
12
13 my $dsn = 'dbi:SQLite:tmp.db';
14
15 my @expect;
16
17 sub sort_set {
18   sort { $a->{name} cmp $b->{name} } @_
19 }
20
21 {
22   unlink('tmp.db');
23   my $dbh = DBI->connect($dsn);
24   $dbh->do(q{
25     CREATE TABLE person (
26       id INTEGER NOT NULL PRIMARY KEY,
27       name VARCHAR(255) NOT NULL
28     )
29   });
30   my $pop = $dbh->prepare(q{INSERT INTO person (name) VALUES (?)});
31   my @names = qw(Joe Jim Bob Pterry);
32   $pop->execute($_) for @names;
33   @expect = sort_set do {
34     my $id = 0; map +{ id => ++$id, name => $_ }, @names
35   };
36 }
37
38 sub make_set {
39   my ($set, $crud) = @_;
40   DBIx::Data::Collection::Set->new(
41     set_over => [ 'id' ],
42     store => DBIx::Data::Store::CRUD->new(
43       raw_store => DBIx::Data::Store->connect($dsn),
44       select_sql => q{SELECT id, name FROM person},
45       select_column_order => [ qw(id name) ],
46       %$crud,
47     ),
48     %$set
49   );
50 }
51
52 my $set = make_set;
53
54 is_deeply([ sort_set $set->flatten ], \@expect, 'Basic data out ok (flatten)');
55
56 {
57   my $stream = $set->as_stream;
58
59   my @got; while (my ($next) = $stream->next) { push @got, $next }
60
61   is_deeply([ sort_set @got ], \@expect, 'Basic data out ok (stream)');
62 }
63
64 $set = make_set { class => 'Spoon' };
65
66 is_deeply(
67   [ sort_set $set->flatten ],
68   [ map { bless({ %$_ }, 'Spoon') } @expect ],
69   'Basic data with class out ok'
70 );
71
72 $set = make_set {}, {
73   insert_sql => q{INSERT INTO person (name) VALUES (?) },
74   insert_argument_order => [ 'name' ],
75   insert_command_constructor => sub {
76     require DBIx::Data::Store::Command::Insert::LastInsertId;
77     my $self = shift;
78     DBIx::Data::Store::Command::Insert::LastInsertId->new(
79       id_column => 'id',
80       raw_store => $self->raw_store,
81       insert_call_command => $self->raw_store->new_call_command(@_)
82     );
83   }
84 };
85
86 my $doug = $set->add({ name => 'Doug' });
87
88 ok($doug->{id}, 'id filled out in new row');
89
90 my ($set_doug) = grep $_->{name} eq 'Doug', $set->flatten;
91
92 ok($set_doug, 'new row exists in flatten');
93
94 cmp_ok(refaddr($doug), '==', refaddr($set_doug), 'Same hashref returned');
95
96 done_testing;