X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~yarrgweb/git?p=ypp-sc-tools.db-test.git;a=blobdiff_plain;f=yarrg%2FCommodsDatabase.pm;h=d978358e4460e70c6e6e676b53a93817550238d3;hp=79744cede7254daabbb07cd0db1941d2e0b7eae2;hb=ee1e57fa0fab5d840206d73a3968fd59d7fa7127;hpb=59bee7afb77216585b904bd20f17e71005e9778c diff --git a/yarrg/CommodsDatabase.pm b/yarrg/CommodsDatabase.pm index 79744ce..d978358 100644 --- a/yarrg/CommodsDatabase.pm +++ b/yarrg/CommodsDatabase.pm @@ -45,7 +45,8 @@ BEGIN { @ISA = qw(Exporter); @EXPORT = qw(&db_setocean &db_writer &db_connect $dbh &db_filename &db_doall &db_onconflict - &dbr_filename &dbr_connect); + &dbr_filename &dbr_connect &db_connect_core + &db_chkcommit &db_check_referential_integrity); %EXPORT_TAGS = ( ); @EXPORT_OK = qw(); @@ -57,10 +58,10 @@ sub dbr_filename ($$) { } sub dbr_connect ($$) { my ($datadir,$ocean) = @_; - return connect_core(dbr_filename($datadir,$ocean)); + return db_connect_core(dbr_filename($datadir,$ocean)); } -sub connect_core ($) { +sub db_connect_core ($) { my ($fn)= @_; my $h= DBI->connect("dbi:SQLite:$fn",'','', { AutoCommit=>0, @@ -110,7 +111,7 @@ sub db_writer () { } sub db_connect () { - $dbh= connect_core($dbfn); + $dbh= db_connect_core($dbfn); } sub db_doall ($) { @@ -119,4 +120,111 @@ sub db_doall ($) { } } +#---------- referential integrity constraints ---------- + +# SQLite doesn't support foreign key constraints so we do it by steam: + +sub nooutput ($) { + my ($stmts) = @_; + my $ekindcount= 0; + my $letxt= ''; + foreach my $stmt (split /\;/, $stmts) { + next unless $stmt =~ /\S/; + + my $etxt= ''; + $stmt =~ s/^([ \t]*\#.*)$/ $etxt .= $1."\n"; ''; /mge; + $etxt= $letxt unless length $etxt; + $letxt= $etxt; + + $stmt =~ s/^\s+//; $stmt =~ s/\s+$//; + my $sth= $dbh->prepare($stmt); + $sth->execute(); + my $row; + my $ecount= 0; + my @cols= @{ $sth->{NAME_lc} }; + my $w= 11; + while ($row= $sth->fetchrow_hashref) { + if (!$ecount++) { + print STDERR "REFERENTIAL INTEGRITY ERROR\n"; + print STDERR "\n$etxt\n $stmt\n\n"; + printf STDERR "|%-${w}s", $_ foreach @cols; print STDERR "|\n"; + print STDERR "+",('-'x$w) foreach @cols; print STDERR "+\n"; + } + if ($ecount>5) { print STDERR "...\n"; last; } + printf STDERR "|%-$w.${w}s", + (defined $row->{$_} ? $row->{$_} : 'NULL') + foreach @cols; + print STDERR "\n"; + } + next unless $ecount; + + $ekindcount++; + print STDERR "\n\n"; + } + die "REFERENTIAL INTEGRITY ERRORS $ekindcount\n" + if $ekindcount; +} + +sub db_check_referential_integrity () { + foreach my $bs (qw(buy sell)) { + nooutput(< 1; + +END +} + +sub db_chkcommit () { + db_check_referential_integrity(); + $dbh->commit(); +} + 1;