From d51ced99b022d1ac09b1c8be8deeb88c6c77b7f1 Mon Sep 17 00:00:00 2001
From: Garet Halliday <ghalliday@gfxlabs.io>
Date: Thu, 29 Sep 2022 16:15:04 -0500
Subject: [PATCH] route unterminated transactions to primary

---
 lib/gat/database/query_router/query_router.go | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/lib/gat/database/query_router/query_router.go b/lib/gat/database/query_router/query_router.go
index 859e2ba0..e66ea327 100644
--- a/lib/gat/database/query_router/query_router.go
+++ b/lib/gat/database/query_router/query_router.go
@@ -7,7 +7,6 @@ import (
 	"gfx.cafe/gfx/pggat/lib/util/cmux"
 	"gfx.cafe/ghalliday1/pg3p"
 	"gfx.cafe/ghalliday1/pg3p/lex"
-	"git.tuxpa.in/a/zlog/log"
 	"strconv"
 	"unicode"
 	"unicode/utf8"
@@ -88,7 +87,7 @@ func (r *QueryRouter) InferRole(query string) (config.ServerRole, error) {
 	}
 	// parse the query
 	tokens := r.parser.Lex(query)
-	log.Printf("route %+v", tokens)
+	depth := 0
 	for _, token := range tokens {
 		switch token.Token {
 		case lex.KeywordUpdate,
@@ -98,8 +97,21 @@ func (r *QueryRouter) InferRole(query string) (config.ServerRole, error) {
 			lex.KeywordCreate,
 			lex.KeywordTruncate:
 			return config.SERVERROLE_PRIMARY, nil
+		case lex.KeywordBegin:
+			depth += 1
+		case lex.KeywordCase:
+			if depth > 0 {
+				depth += 1
+			}
+		case lex.KeywordEnd:
+			if depth > 0 {
+				depth -= 1
+			}
 		}
 	}
+	if depth > 0 {
+		return config.SERVERROLE_PRIMARY, nil
+	}
 	return config.SERVERROLE_REPLICA, nil
 }
 
-- 
GitLab