add basic inflation wrapper and simple inflator
[dbsrgits/DBIx-Data-Store.git] / t / crud.t
CommitLineData
54bed31b 1use strictures 1;
2use Test::More;
3
4use DBIx::Data::Store::CRUD;
5use DBIx::Data::Store::Raw;
6
7use DBI;
8use Scalar::Util qw(refaddr);
9
10sub sort_set {
11 sort { $a->{name} cmp $b->{name} } @_
12}
13
14my $dsn = 'dbi:SQLite:tmp.db';
15
16sub setup_dbh {
17 unlink('tmp.db');
18 return DBI->connect($dsn, undef, undef, { RaiseError => 1 })
19}
20
21sub setup_db {
22 my $dbh = setup_dbh;
23 $dbh->do(q{
24 CREATE TABLE names (
25 id INTEGER NOT NULL PRIMARY KEY,
26 name VARCHAR(255) NOT NULL
27 )
28 });
29 #my $pop = $dbh->prepare(q{INSERT INTO person (name) VALUES (?)});
30 #my @names = qw(Joe Jim Bob Pterry);
31 #$pop->execute($_) for @names;
32 #return sort_set do {
33 # my $id = 0; map +{ id => ++$id, name => $_ }, @names
34 #};
35}
36
37my $db_store = DBIx::Data::Store::Raw->connect($dsn);
38
39sub raw_store { $db_store }
40
41sub make_store {
42 my ($crud) = @_;
43 DBIx::Data::Store::CRUD->new({
44 raw => $db_store,
45 sql => {
46 select_all => 'SELECT id, name FROM names',
47 delete_all => 'DELETE FROM names',
48 select_one => 'SELECT id, name FROM names WHERE id = ?',
937bf544 49 insert_one => sub {
50 my ($store, undef, $dbh, $args) = @_;
51 $store->_sth_for($dbh, 'INSERT INTO names (name) VALUES (?)', $args);
34b924ec 52 [ $dbh->last_insert_id(undef,undef,undef,undef), @$args ];
937bf544 53 },
54bed31b 54 update_one => 'UPDATE names SET name = ? WHERE id = ?',
55 delete_one => 'DELETE FROM names WHERE id = ?',
56 },
57 });
58}
59
34b924ec 60sub run_tests {
61 setup_db;
54bed31b 62
34b924ec 63 my $store = make_store;
54bed31b 64
34b924ec 65 is_deeply([$store->flatten], [], 'Empty set');
54bed31b 66
34b924ec 67 is_deeply($store->add(['Bob']), [1,'Bob'], 'Add record');
54bed31b 68
34b924ec 69 is_deeply([$store->flatten], [[1,'Bob']], 'One member');
54bed31b 70
34b924ec 71 is_deeply($store->get([1]), [1,'Bob'], 'Retrieve by key');
54bed31b 72
34b924ec 73 $store->replace([1],['Robert']);
54bed31b 74
34b924ec 75 is_deeply([$store->flatten], [[1,'Robert']], 'Name changed (all)');
54bed31b 76
34b924ec 77 is_deeply($store->get([1]), [1,'Robert'], 'Retrieve by key');
54bed31b 78
34b924ec 79 $store->add([$_]) for qw(Joe James Jim);
54bed31b 80
34b924ec 81 my $flatsort = sub {
82 [ sort { $a->[0] <=> $b->[0] } $store->flatten ]
83 };
54bed31b 84
34b924ec 85 is_deeply($flatsort->(), [
86 [1,'Robert'],[2,'Joe'],[3,'James'],[4,'Jim']
87 ], 'Four members');
54bed31b 88
34b924ec 89 is_deeply($store->get([3]),[3,'James'], 'Retrieve by key');
54bed31b 90
34b924ec 91 $store->remove([3]);
54bed31b 92
34b924ec 93 is_deeply($flatsort->(), [
94 [1,'Robert'],[2,'Joe'],[4,'Jim']
95 ], 'Three members left');
54bed31b 96
34b924ec 97 done_testing;
98}
99
100run_tests unless caller;