The following code when the 'update stock' condition returns 0, executes sql_error()'s sql 'insert into sql_error' AND dosql()'s 'insert into stock_valid' ,despite that the first statement of sql_error() is $dbh->rollback. I know that wrapping do_sql()'s sql statements in $dbh->begin_work would probably make it work, but I'm interested in the background of why it is happening.

I have a theory that every 'do' statement does start a new implicit transaction. So let's say that do(insert into stock_valid) is T1 and do(update stock) is T2. Then, T1 is rolled back when the rollback of sql_error() is hit, while T2 is not rolled back and instead is committed when $dbh->commit; of sql_error() is hit.

My 2cents. What do you think?

$dbh->{AutoCommit}=0; $dbh->{RaiseError}=1; $dbh->{HandleError}=\&handle_error; sub do_sql() { $dbh->do(qq{ insert into stock_valid (last_year,orderid,suppliervatno, code,executedquantity,productprice) values ( $last_year,$orderid,$suppliervatno, $code,$executedquantity,$productprice ) }); my $rowsupdated=$dbh->do(qq{ update stock set quantity=quantity+$executedquantity where code=$code }); if ($rowsupdated==0) { sql_error($order,'no rows found','LocalError'); } $dbh->commit; $dbh->disconnect; } sub sql_error() { $dbh->rollback; my $orderid=$dbh->quote(shift); my $resultreason=$dbh->quote(shift); my $resultcode=$dbh->quote(shift); $dbh->do(qq{ insert into sql_error (orderid,resultreason,resultcode) values ( $orderid,$resultreason,$resultcode ) }); $dbh->commit; $dbh->disconnect; die; }

Grandfather replaced pre tags with Code tags and fixed paragraphing.


In reply to Does each DBI 'do' start a new transaction? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.