|
| 1 | +""" |
| 2 | +Code for connecting to Big Query database |
| 3 | +""" |
| 4 | +import logging |
| 5 | +import os |
| 6 | + |
| 7 | +import google.cloud.bigquery as bq |
| 8 | +from google.cloud import pubsub_v1 |
| 9 | +from db.python.utils import InternalError |
| 10 | + |
| 11 | +logging.basicConfig(level=logging.DEBUG) |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class BqConnection: |
| 16 | + """Stores a Big Query DB connection, project and author""" |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + author: str, |
| 21 | + ): |
| 22 | + self.gcp_project = os.getenv('METAMIST_GCP_PROJECT') |
| 23 | + self.connection: bq.Client = bq.Client(project=self.gcp_project) |
| 24 | + self.author: str = author |
| 25 | + |
| 26 | + @staticmethod |
| 27 | + async def get_connection_no_project(author: str): |
| 28 | + """Get a db connection from a project and user""" |
| 29 | + # maybe it makes sense to perform permission checks here too |
| 30 | + logger.debug(f'Authenticate no-project connection with {author!r}') |
| 31 | + |
| 32 | + # we don't authenticate project-less connection, but rely on the |
| 33 | + # the endpoint to validate the resources |
| 34 | + |
| 35 | + return BqConnection(author=author) |
| 36 | + |
| 37 | + |
| 38 | +class BqDbBase: |
| 39 | + """Base class for big query database subclasses""" |
| 40 | + |
| 41 | + def __init__(self, connection: BqConnection): |
| 42 | + if connection is None: |
| 43 | + raise InternalError( |
| 44 | + f'No connection was provided to the table {self.__class__.__name__!r}' |
| 45 | + ) |
| 46 | + if not isinstance(connection, BqConnection): |
| 47 | + raise InternalError( |
| 48 | + f'Expected connection type Connection, received {type(connection)}, ' |
| 49 | + f'did you mean to call self._connection?' |
| 50 | + ) |
| 51 | + |
| 52 | + self._connection = connection |
| 53 | + |
| 54 | + |
| 55 | +class PubSubConnection: |
| 56 | + """Stores a PubSub connection, project and author""" |
| 57 | + |
| 58 | + def __init__( |
| 59 | + self, |
| 60 | + author: str, |
| 61 | + topic: str, |
| 62 | + ): |
| 63 | + self.client: pubsub_v1.PublisherClient = pubsub_v1.PublisherClient() |
| 64 | + self.author: str = author |
| 65 | + self.topic: str = os.getenv('METAMIST_GCP_PROJECT') + topic |
| 66 | + |
| 67 | + @staticmethod |
| 68 | + async def get_connection_no_project(author: str): |
| 69 | + """Get a pubsub connection from a project and user""" |
| 70 | + # maybe it makes sense to perform permission checks here too |
| 71 | + logger.debug(f'Authenticate no-project connection with {author!r}') |
| 72 | + |
| 73 | + # we don't authenticate project-less connection, but rely on the |
| 74 | + # the endpoint to validate the resources |
| 75 | + |
| 76 | + return PubSubConnection(author=author) |
0 commit comments