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