Frage

So I've inherited a large c++ code base which does a lot of mysql work. The code always disables autocommit and tends to have functions which look like this:

int function() {
    if(mysql_real_query(conn, ...)) {
        return -1;
    }

    if(mysql_real_query(conn, ...)) {
        return -1;
    }

    mysql_commit(conn);
    return 0;
}

Obviously, the intention here is that the commit only happens if the queries are successful. But what happens if one of them isn't? Eventually, the mysql connection is properly closed, but there is no rollbacks in the code.

So when it closes, will it basically just commit any changes that were successful? Or will it rollback as if nothing happened?

My gut says that it makes sense to have a rollback if the second query fails in order to "undo" the successful first query. So this function ends up be transactional.

Of course, I find this code to be inherently broken because later other mysql code could do a commit leaving things in a "weird" state if some previous work failed. But before I go and change the behavior of the program, I wanted to make sure I understood what the current behavior was.

War es hilfreich?

Lösung

As Marc B said, this is actually easy enough to test. I was hoping for someone to be able to point at an authoritative source, but testing seems to be reasonable enough:

So anyway, I tried the following code:

MYSQL *conn = mysql_init(NULL);
mysql_real_connect(conn, host, use, password, database, 0, NULL, 0);
mysql_autocommit(conn, 0);
mysql_query(conn, "INSERT INTO test VALUES(1)");
mysql_query(conn, "INSERT INTO test VALUES(2)");
mysql_query(conn, "INSERT INTO test VALUES(3)");
mysql_query(conn, "INSERT INTO test VALUES(4)");
mysql_close(conn);

simple enough, turn off auto-commit, do a bunch of inserts, and never commit. In this case, result is that the queries are effectively rolled back. When I query the DB, the rows are not there.

Obviously simply adding a mysql_commit(conn); right before the mysql_close(conn); does in fact cause the rows to be created.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top