Skip to content

Commit

Permalink
Split read and write db backends (#41)
Browse files Browse the repository at this point in the history
* Bug fix

* Direct custom sql query to the read db. All other requests are going to the default db
  • Loading branch information
ruslan33 authored Feb 6, 2025
1 parent fb7a415 commit 67b305e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
14 changes: 12 additions & 2 deletions cdb_rest/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import sys
import time
import random

from django.conf import settings

from django.shortcuts import get_object_or_404
from decimal import Decimal
Expand All @@ -13,7 +16,7 @@
# from rest_framework.permissions import IsAuthenticated, AllowAny
# from cdb_rest.authentication import CustomJWTAuthentication

from django.db import transaction, connection
from django.db import transaction, connection, connections

from django.db.models import Prefetch
from django.db.models import Q
Expand Down Expand Up @@ -522,12 +525,19 @@ def list(self, request):
class PayloadIOVsSQLListAPIView(ListAPIView):

def list(self, request):
with connection.cursor() as cursor:
# Get available read databases (excluding "default")
read_dbs = [db for db in settings.DATABASES.keys() if db.startswith("read_db_")]

# If at least one read database is available, use it; otherwise, use "default"
read_db = random.choice(read_dbs) if read_dbs else "default"

with connections[read_db].cursor() as cursor:
cursor.execute(cdb_rest.queries.get_payload_iovs,
{'my_major_iov': self.request.GET.get('majorIOV'),
'my_minor_iov': self.request.GET.get('minorIOV'),
'my_gt': self.request.GET.get('gtName')})
row = cursor.fetchall()

return Response(row)


Expand Down
9 changes: 5 additions & 4 deletions nopayloaddb/db_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
class ReadWriteRouter:
def db_for_read(self, model, **hints):
"""Route read queries to one of the read databases."""
db = random.choice(['read_db_1', 'read_db_2'])
# Redirect everything to default
#db = random.choice(['read_db_1', 'read_db_2'])
# Check if request information is available
request = get_current_request()
if request and request.method == 'GET':
return db
#request = get_current_request()
#if request and request.method == 'GET':
# return db
return 'default'

def db_for_write(self, model, **hints):
Expand Down

0 comments on commit 67b305e

Please sign in to comment.