$OpenBSD: patch-dbd_sqlite3_connection_c,v 1.1.1.1 2012/08/16 15:21:30 jasper Exp $

Fix DBD.SQLite3 transaction handling
From upstream svn rev 75

--- dbd/sqlite3/connection.c.orig	Sat May  1 06:25:12 2010
+++ dbd/sqlite3/connection.c	Sun Jul 22 22:23:54 2012
@@ -9,20 +9,37 @@ static int run(connection_t *conn, const char *command
 }
 
 static int commit(connection_t *conn) {
-    return run(conn, "COMMIT");
+    conn->txn_in_progress = 0;
+    return run(conn, "COMMIT TRANSACTION");
 }
 
 
 static int begin(connection_t *conn) {
-    return run(conn, "BEGIN");
-}
+    int err = 0;
 
+    if (conn->txn_in_progress) {
+        err = 0;
+    } else {
+        conn->txn_in_progress = 1;
+        err = run(conn, "BEGIN TRANSACTION");
+    }
 
+    return err;
+}
+
 static int rollback(connection_t *conn) {
-    return run(conn, "ROLLBACK");
+    conn->txn_in_progress = 0;
+    return run(conn, "ROLLBACK TRANSACTION");
 }
 
+int try_begin_transaction(connection_t *conn) {
+    if (conn->autocommit) {
+        return 1;
+    }
 
+    return begin(conn) == 0;
+}
+
 /* 
  * connection,err = DBD.SQLite3.New(dbfile)
  */
@@ -50,7 +67,7 @@ static int connection_new(lua_State *L) {
     }
 
     conn->autocommit = 0;
-    begin(conn);
+    conn->txn_in_progress = 0;
 
     luaL_getmetatable(L, DBD_SQLITE_CONNECTION);
     lua_setmetatable(L, -2);
@@ -67,10 +84,13 @@ static int connection_autocommit(lua_State *L) {
     int err = 1;
 
     if (conn->sqlite) {
-	if (on)
+	if (on) {
 	    err = rollback(conn);
+        }
+        /*
 	else
 	    err = begin(conn);
+        */
 
 	conn->autocommit = on;	
     }
@@ -88,6 +108,7 @@ static int connection_close(lua_State *L) {
     int disconnect = 0;   
 
     if (conn->sqlite) {
+        rollback(conn);
 	sqlite3_close(conn->sqlite);
 	disconnect = 1;
 	conn->sqlite = NULL;
@@ -105,12 +126,7 @@ static int connection_commit(lua_State *L) {
     int err = 1;
 
     if (conn->sqlite) {
-	commit(conn);
-
-	if (!conn->autocommit)
-	    err = begin(conn);
-	else
-	    err = 1;
+	err = commit(conn);
     }
 
     lua_pushboolean(L, !err);
@@ -176,12 +192,14 @@ static int connection_rollback(lua_State *L) {
     int err = 1;
 
     if (conn->sqlite) {
-	rollback(conn);
+	err =rollback(conn);
 
+        /*
 	if (!conn->autocommit)
 	    err = begin(conn);
 	else
 	    err = 1;
+        */
     }
 
     lua_pushboolean(L, !err);
