Skip to content

Instantly share code, notes, and snippets.

@javiergarciad
Created June 28, 2023 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javiergarciad/21ad7919c91e5ba46e017fe4fe23960f to your computer and use it in GitHub Desktop.
Save javiergarciad/21ad7919c91e5ba46e017fe4fe23960f to your computer and use it in GitHub Desktop.
ClickHouse Database handler
import logging
from clickhouse_driver import Client, connect, errors
from clickhouse_driver.dbapi.cursor import Cursor
logger = logging.getLogger(__name__)
class ClickHouseDB:
"""
Class for working with a ClickHouse server
"""
def __init__(self, name: str, url: str) -> None:
self.name = name
self.url = url
self._client = None
self._cursor = None
def client(self) -> Client | errors.Error:
"""
Returns a ClickHouse client. If a client has already been created,
the existing client is returned. Otherwise, a new client is created.
Raises:
errors.Error: If there is an error creating the client.
"""
if self._client is None:
try:
self._client = Client.from_url(self.url)
except errors.Error as e:
logger.error(str(e))
raise
return self._client
def cursor(self) -> Cursor | errors.Error:
"""
Returns a ClickHouse cursor. If a cursor has already been created,
the existing cursor is returned. Otherwise, a new cursor is created.
Raises:
errors.Error: If there is an error creating the cursor.
"""
if self._cursor is None:
try:
conn = connect(self.url)
self._cursor = conn.cursor()
except errors.Error as e:
logger.error(str(e))
raise
return self._cursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment