## Copyright (c) 2016-2024 Deephaven Data Labs and Patent Pending#"""The dbc package includes the modules and functions for using external databases with Deephaven."""fromtypingimportAny,Literalimportdeephaven.arrowasdharrowfromdeephavenimportDHErrorfromdeephaven.tableimportTable
[docs]defread_sql(conn:Any,query:str,driver:Literal["odbc","adbc","connectorx"]="connectorx")->Table:"""Executes the provided SQL query via a supported driver and returns a Deephaven table. Args: conn (Any): must either be a connection string for the given driver or a Turbodbc/ADBC DBAPI Connection object; when it is a Connection object, the driver argument will be ignored. query (str): SQL query statement driver: (str): the driver to use, supported drivers are "odbc", "adbc", "connectorx", default is "connectorx" Returns: a new Table Raises: DHError """ifisinstance(conn,str):ifdriver=="connectorx":try:importconnectorxascxexceptImportError:raiseDHError(message="import connectorx failed, please install it first.")try:pa_table=cx.read_sql(conn=conn,query=query,return_type="arrow")returndharrow.to_table(pa_table)exceptExceptionase:raiseDHError(e,message="failed to get a Arrow table from ConnectorX.")fromeelifdriver=="odbc":fromdeephaven.dbc.odbcimportread_cursorimportturbodbcwithturbodbc.connect(connection_string=conn)asconn:withconn.cursor()ascursor:cursor.execute(query)returnread_cursor(cursor)elifdriver=="adbc":fromdeephaven.dbc.adbcimportread_cursorifnotconn:importadbc_driver_sqlite.dbapiasdbapielifconn.strip().startswith("postgresql:"):importadbc_driver_postgresql.dbapiasdbapielse:raiseDHError(message=f"unsupported ADBC connection string {conn}")withdbapi.connect(conn)asdbconn:withdbconn.cursor()ascursor:cursor.execute(query)returnread_cursor(cursor)else:raiseDHError(message=f"unsupported driver {driver}")else:try:importadbc_driver_manager.dbapiasdbapiifisinstance(conn,dbapi.Connection):fromdeephaven.dbc.adbcimportread_cursorwithconn.cursor()ascursor:cursor.execute(query)returnread_cursor(cursor)exceptImportError:passtry:importturbodbc.connectionifisinstance(conn,turbodbc.connection.Connection):fromdeephaven.dbc.odbcimportread_cursorwithconn.cursor()ascursor:cursor.execute(query)returnread_cursor(cursor)exceptImportError:passraiseDHError(message=f"invalid conn argument {conn}")