From 2d198c091036767fdad1c3cd79f1bba4664682ea Mon Sep 17 00:00:00 2001 From: Adam Chlipala Date: Sat, 17 Oct 2015 10:49:25 -0400 Subject: Start of support for surviving database-server restarts, for Postgres --- src/c/urweb.c | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) (limited to 'src/c/urweb.c') diff --git a/src/c/urweb.c b/src/c/urweb.c index 6d3836f1..4ce469bd 100644 --- a/src/c/urweb.c +++ b/src/c/urweb.c @@ -797,10 +797,37 @@ failure_kind uw_begin(uw_context ctx, char *path) { 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; } } -- cgit v1.2.3