Debian Codegraph @

t/30_insertfetch.t

raw
1 #!/usr/local/bin/perl
2
3 # Test row insertion and retrieval
4
5 use strict;
6 use warnings;
7 use Test::More;
8
9 BEGIN { use_ok ("DBI") }
10 do "./t/lib.pl";
11
12 my @tbl_def = (
13 [ "id", "INTEGER", 4, 0 ],
14 [ "name", "CHAR", 64, 0 ],
15 [ "val", "INTEGER", 4, 0 ],
16 [ "txt", "CHAR", 64, 0 ],
17 );
18
19 ok (my $dbh = Connect (), "connect");
20
21 ok (my $tbl = FindNewTable ($dbh), "find new test table");
22 $tbl ||= "tmp99";
23 eval {
24 local $SIG{__WARN__} = sub {};
25 $dbh->do ("drop table $tbl");
26 };
27
28 like (my $def = TableDefinition ($tbl, @tbl_def),
29 qr{^create table $tbl}i, "table definition");
30
31 my $sz = 0;
32 ok ($dbh->do ($def), "create table");
33 my $tbl_file = DbFile ($tbl);
34 ok ($sz = -s $tbl_file, "file exists");
35
36 ok ($dbh->do ("insert into $tbl values ".
37 "(1, 'Alligator Descartes', 1111, 'Some Text')"), "insert");
38 ok ($sz < -s $tbl_file, "file grew");
39 $sz = -s $tbl_file;
40
41 ok ($dbh->do ("insert into $tbl (id, name, val, txt) values ".
42 "(2, 'Crocodile Dundee', 2222, 'Down Under')"), "insert with field names");
43 ok ($sz < -s $tbl_file, "file grew");
44
45 ok (my $sth = $dbh->prepare ("select * from $tbl where id = 1"), "prepare");
46 is (ref $sth, "DBI::st", "handle type");
47
48 ok ($sth->execute, "execute");
49
50 ok (my $row = $sth->fetch, "fetch");
51 is (ref $row, "ARRAY", "returned a list");
52 is ($sth->errstr, undef, "no error");
53
54 is_deeply ($row, [ 1, "Alligator Descartes", 1111, "Some Text" ], "content");
55
56 ok ($sth->finish, "finish");
57 undef $sth;
58
59 # Try some other capitilization
60 ok ($dbh->do ("DELETE FROM $tbl WHERE id = 1"), "delete");
61
62 # Now, try SELECT'ing the row out. This should fail.
63 ok ($sth = $dbh->prepare ("select * from $tbl where id = 1"), "prepare");
64 is (ref $sth, "DBI::st", "handle type");
65
66 ok ($sth->execute, "execute");
67 is ($sth->fetch, undef, "fetch");
68 is ($sth->errstr, undef, "error"); # ???
69
70 ok ($sth->finish, "finish");
71 undef $sth;
72
73 ok ($sth = $dbh->prepare ("insert into $tbl values (?, ?, ?, ?)"), "prepare insert");
74 ok ($sth->execute (3, "Babar", 3333, "Elephant"), "insert prepared");
75 ok ($sth->finish, "finish");
76 undef $sth;
77
78 ok ($sth = $dbh->prepare ("insert into $tbl (id, name, val, txt) values (?, ?, ?, ?)"), "prepare insert with field names");
79 ok ($sth->execute (4, "Vischje", 33, "in het riet"), "insert prepared");
80 ok ($sth->finish, "finish");
81 undef $sth;
82
83 ok ($dbh->do ("delete from $tbl"), "delete all");
84 ok ($dbh->do ("insert into $tbl (id) values (0)"), "insert just one field");
85 { local (@ARGV) = DbFile ($tbl);
86 my @csv = <>;
87 s/\r?\n\Z// for @csv;
88 is (scalar @csv, 2, "Just two lines");
89 is ($csv[0], "id,name,val,txt", "header");
90 is ($csv[1], "0,,,", "data");
91 }
92
93 ok ($dbh->do ("drop table $tbl"), "drop");
94 ok ($dbh->disconnect, "disconnect");
95
96 done_testing ();