diff src/c/urweb.c @ 2176:d2a98983f502

Start of support for surviving database-server restarts, for Postgres
author Adam Chlipala <adam@chlipala.net>
date Sat, 17 Oct 2015 10:49:25 -0400
parents 8a01e8f21de9
children 00cf8214c2e3
line wrap: on
line diff
--- a/src/c/urweb.c	Thu Oct 15 07:52:37 2015 -0400
+++ b/src/c/urweb.c	Sat Oct 17 10:49:25 2015 -0400
@@ -797,10 +797,37 @@
   return r;
 }
 
+static void uw_try_reconnecting(uw_context ctx) {
+  // Hm, error starting transaction.
+  // Maybe the database server died but has since come back up.
+  // Let's try starting from scratch.
+  if (ctx->db) {
+    ctx->app->db_close(ctx);
+    ctx->db = NULL;
+  }
+  ctx->app->db_init(ctx);
+
+  if (!ctx->db)
+    uw_error(ctx, FATAL, "Error reopening database connection");
+}
+
+int uw_try_reconnecting_if_at_most_one(uw_context ctx) {
+  if (ctx->at_most_one_query) {
+    uw_try_reconnecting(ctx);
+    return 1;
+  } else
+    return 0;
+}
+
 void uw_ensure_transaction(uw_context ctx) {
   if (!ctx->transaction_started && !ctx->at_most_one_query) {
-    if (ctx->app->db_begin(ctx, ctx->could_write_db))
-      uw_error(ctx, BOUNDED_RETRY, "Error running SQL BEGIN");
+    if (!ctx->db || ctx->app->db_begin(ctx, ctx->could_write_db)) {
+      uw_try_reconnecting(ctx);
+
+      if (ctx->app->db_begin(ctx, ctx->could_write_db))
+        uw_error(ctx, FATAL, "Error running SQL BEGIN");
+    }
+
     ctx->transaction_started = 1;
   }
 }