Advanced Topics#

Connection Redundancy#

connection redundancy, handling of missing nodes#
"""
Connection redundancy, attempts to connect to all hosts from DSN in random order
"""

import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

# Basic connect
C = pyexasol.connect(
    dsn="0.42.42.40..49," + config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    connection_timeout=2,
    debug=True,
    websocket_sslopt=config.websocket_sslopt,
)

Edge Cases#

storing and fetching biggest and smallest values for data types available in Exasol#
"""
Try to read and write minimum and maximum possible values, test various edge cases
"""

import decimal
import pprint
from typing import Any

import examples._config as config
import pyexasol
from pyexasol.data_types import convert_websocket_to_python

printer = pprint.PrettyPrinter(indent=4, width=140)

# Basic connect
C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    websocket_sslopt=config.websocket_sslopt,
)

edge_cases: list[dict[str, Any]] = [
    # Biggest values
    {
        "dec36_0": decimal.Decimal("+" + ("9" * 36)),
        "dec36_36": decimal.Decimal("+0." + ("9" * 36)),
        "dbl": 1.7e308,
        "bl": True,
        "dt": "9999-12-31",
        "ts": "9999-12-31 23:59:59.999",
        "var100": "ひ" * 100,
        "var2000000": "ひ" * 2000000,
    },
    # Smallest values
    {
        "dec36_0": decimal.Decimal("-" + ("9" * 36)),
        "dec36_36": decimal.Decimal("-0." + ("9" * 36)),
        "dbl": -1.7e308,
        "bl": False,
        "dt": "0001-01-01",
        "ts": "0001-01-01 00:00:00",
        "var100": "",
        "var2000000": "ひ",
    },
    # All nulls
    {
        "dec36_0": None,
        "dec36_36": None,
        "dbl": None,
        "bl": None,
        "dt": None,
        "ts": None,
        "var100": None,
        "var2000000": None,
    },
]

insert_q = "INSERT INTO edge_case VALUES ({dec36_0!d}, {dec36_36!d}, {dbl!f}, {bl}, {dt}, {ts}, {var100}, {var2000000})"
select_q = "SELECT dec36_0, dec36_36, dbl, bl, dt, ts, var100, LENGTH(var2000000) AS len_var FROM edge_case"

C.execute("TRUNCATE TABLE edge_case")

# Insert (test formatting)
C.execute(insert_q, edge_cases[0])
C.execute(insert_q, edge_cases[1])
C.execute(insert_q, edge_cases[2])

# Select and fetch
stmt = C.execute(select_q)
printer.pprint(stmt.fetchall())


# Same actions with "convert_websocket_to_python"
C.options["fetch_mapper"] = convert_websocket_to_python
C.execute("TRUNCATE TABLE edge_case")

# Insert (test formatting)
C.execute(insert_q, edge_cases[0])
C.execute(insert_q, edge_cases[1])
C.execute(insert_q, edge_cases[2])

# Select and fetch
stmt = C.execute(select_q)
printer.pprint(stmt.fetchall())

# Import and export
edge_tuples = C.execute("SELECT * FROM edge_case").fetchall()

C.execute("TRUNCATE TABLE edge_case")

C.import_from_iterable(edge_tuples, "edge_case")
stmt = C.last_statement()
print(f"IMPORTED {stmt.rowcount()} rows in {stmt.execution_time}s")

res = C.export_to_list(select_q)
stmt = C.last_statement()
print(f"EXPORTED {stmt.rowcount()} rows in {stmt.execution_time}s")
printer.pprint(res)

# resultSetHandle and data in the same response
stmt = C.execute("SELECT a.* FROM edge_case a, edge_case b, edge_case c, edge_case d")
print(f"Rows total: {stmt.num_rows_total}, rows chunk: {stmt.num_rows_chunk}")
print(f"Rows actually returned {sum(1 for _ in stmt)}")


# Very large query
stmt = C.execute(
    "SELECT {val1} AS val1, {val2} AS val2, {val3} AS val3, {val4} AS val4, {val5} AS val5",
    {
        "val1": edge_cases[0]["var2000000"],
        "val2": edge_cases[0]["var2000000"],
        "val3": edge_cases[0]["var2000000"],
        "val4": edge_cases[0]["var2000000"],
        "val5": edge_cases[0]["var2000000"],
    },
)

print(f"Query length: {len(stmt.query)}")
print(f"Result column length: {len(stmt.fetchone()[0])}")

# Very large query with compression
C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    compression=True,
    encryption=True,
    websocket_sslopt=config.websocket_sslopt,
)

stmt = C.execute(
    "SELECT {val1} AS val1, {val2} AS val2, {val3} AS val3, {val4} AS val4, {val5} AS val5",
    {
        "val1": edge_cases[0]["var2000000"],
        "val2": edge_cases[0]["var2000000"],
        "val3": edge_cases[0]["var2000000"],
        "val4": edge_cases[0]["var2000000"],
        "val5": edge_cases[0]["var2000000"],
    },
)

print(f"Query length: {len(stmt.query)}")
print(f"Result column length: {len(stmt.fetchone()[0])}")

Using DB-API 2.0#

using the DB-API 2.0 facade#
"""Basic usage of the maintained DB-API 2.0 facade."""

import pprint
from contextlib import closing

import examples._config as config
from exasol.driver.websocket import dbapi2

printer = pprint.PrettyPrinter(indent=4, width=140)

USERS_QUERY = "SELECT * FROM users ORDER BY user_id LIMIT 5"

with closing(
    dbapi2.connect(
        dsn=config.dsn,
        username=config.user,
        password=config.password,
        schema=config.schema,
        autocommit=False,
        certificate_validation=False,
    )
) as connection:
    # Query and result operations require an active cursor.
    with connection.cursor() as cursor:
        # Fetch tuples row-by-row as iterator
        cursor.execute(USERS_QUERY)

        while True:
            row = cursor.fetchone()

            if row is None:
                break

            printer.pprint(row)

        # Fetch many
        cursor.execute(USERS_QUERY)
        printer.pprint(cursor.fetchmany(3))
        printer.pprint(cursor.fetchmany(3))

        # Fetch everything in one go
        cursor.execute(USERS_QUERY)
        printer.pprint(cursor.fetchall())

        printer.pprint(cursor.description)
        printer.pprint(cursor.rowcount)

    # The connection remains available after the cursor is closed.
    connection.commit()

SSL Encryption#

SSL-encrypted WebSocket connection and HTTP transport#
"""
Connection with SSL encryption enabled
It works both for WebSocket communication (wss://) and HTTP(S) Transport
"""

import hashlib
import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

# Connect with encryption
C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    encryption=True,
    websocket_sslopt=config.websocket_sslopt,
)

# Basic query
stmt = C.execute("SELECT * FROM users ORDER BY user_id LIMIT 5")
printer.pprint(stmt.fetchall())

# Export to list
users = C.export_to_list("SELECT * FROM users ORDER BY user_id LIMIT 5")
stmt = C.last_statement()
print(f"EXPORTED {stmt.rowcount()} rows in {stmt.execution_time}s")

print(users[0])
print(users[1])

# Import from list
C.import_from_iterable(users, "users_copy")
stmt = C.last_statement()
print(f"IMPORTED {stmt.rowcount()} rows in {stmt.execution_time}s")


# Connect with encryption AND certificate fingerprint check
server_fingerprint = hashlib.sha256(C._ws.sock.getpeercert(True)).hexdigest().upper()
print(f"Server certificate fingerprint: {server_fingerprint}")

if ":" in config.dsn:
    dsn_with_valid_fingerprint = config.dsn.replace(":", f"/{server_fingerprint}:")
    dsn_with_invalid_fingerprint = config.dsn.replace(":", f"/123abc:")
else:
    dsn_with_valid_fingerprint = f"{config.dsn}/{server_fingerprint}"
    dsn_with_invalid_fingerprint = f"{config.dsn}/123abc"

C = pyexasol.connect(
    dsn=dsn_with_valid_fingerprint,
    user=config.user,
    password=config.password,
    schema=config.schema,
    encryption=True,
    websocket_sslopt=config.websocket_sslopt,
)
print(f"Encrypted connection with fingerprint validation was established")


# Invalid fingerprint causes exception
try:
    pyexasol.connect(
        dsn=dsn_with_invalid_fingerprint,
        user=config.user,
        password=config.password,
        schema=config.schema,
        encryption=True,
        websocket_sslopt=config.websocket_sslopt,
    )
except pyexasol.ExaConnectionFailedError as e:
    print(e)

# Valid fingerprint without encryption causes exception
try:
    pyexasol.connect(
        dsn=dsn_with_valid_fingerprint,
        user=config.user,
        password=config.password,
        schema=config.schema,
        websocket_sslopt=config.websocket_sslopt,
        encryption=False,
    )
except pyexasol.ExaConnectionDsnError as e:
    print(e)

Custom Session Parameters#

passing custom session parameters client_name, client_version, etc.#
"""
Custom client name, client version, other session parameters
Useful for logging
"""

import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

# Normal session
C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    fetch_dict=True,
    websocket_sslopt=config.websocket_sslopt,
)

st = C.execute("SELECT * FROM EXA_DBA_SESSIONS WHERE session_id=CURRENT_SESSION")
printer.pprint(st.fetchall())

C.close()

# Modified session
C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    fetch_dict=True,
    client_name="MyCustomClient",
    client_version="1.2.3",
    client_os_username="small_cat",
    websocket_sslopt=config.websocket_sslopt,
)

st = C.execute("SELECT * FROM EXA_DBA_SESSIONS WHERE session_id=CURRENT_SESSION")
printer.pprint(st.fetchall())

C.close()

Local Config File#

connect using local config file#
"""
Local config file
"""

import configparser
import pathlib
import pprint
import tempfile
from typing import Any

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

# Generate tmp file with sample config
with tempfile.TemporaryDirectory() as tempdir:
    tempdir_path = pathlib.Path(tempdir)

    handle = open(tempdir_path / "test.ini", "w+", encoding="utf-8")
    parser = configparser.ConfigParser()

    # WARNING: Storing the password in plain text, as done here, is NOT proper
    # practice. It is only done to keep this example self-contained, as the file
    # is temporary. Do not do this with a real config file.
    # Instead, leave the password out of the file and provide it when connecting,
    # since extra arguments to `connect_local_config` override the file's values:
    #
    #   import getpass
    #   C = pyexasol.connect_local_config(
    #       "test1", password=getpass.getpass("Exasol password: ")
    #   )
    #
    # Another option includes reading from a secret store, e.g. the `keyring` package
    # or your platform's secret manager.
    local_config: dict[str, Any] = {
        "dsn": config.dsn,
        "user": config.user,
        "password": config.password,
        "schema": config.schema,
        "compression": True,
        "encryption": True,
        "socket_timeout": 20,
    }
    parser["test1"] = local_config

    parser.write(handle)
    handle.seek(0)

    print(handle.read())
    handle.close()

    # Open connection using config file
    C = pyexasol.connect_local_config(
        "test1", config_path=handle.name, websocket_sslopt=config.websocket_sslopt
    )

    # Basic query
    stmt = C.execute("SELECT * FROM users ORDER BY user_id LIMIT 5")
    printer.pprint(stmt.fetchall())

Profiling#

last query profiling#
"""
Profiling with and without details
"""

import json
import pprint
import sys

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    websocket_sslopt=config.websocket_sslopt,
)

C.execute("ALTER SESSION SET QUERY_CACHE = 'OFF'")
C.execute("ALTER SESSION SET PROFILE = 'ON'")

# Normal profiling
stmt = C.execute("""
    SELECT u.user_id, sum(p.gross_amt) AS total_gross_amt
    FROM users u
        LEFT JOIN payments p ON (u.user_id=p.user_id)
    GROUP BY 1
    ORDER BY 2 DESC NULLS LAST
    LIMIT 10
""")

printer.pprint(stmt.fetchall())
json.dump(C.ext.explain_last(), sys.stdout, indent=4)

# Profiling with extra details per node (IPROC column)
C.execute("""
    SELECT u.user_id, sum(p.gross_amt) AS total_gross_amt
    FROM users u
        LEFT JOIN payments p ON (u.user_id=p.user_id)
    GROUP BY 1
    ORDER BY 2 DESC NULLS LAST
    LIMIT 10
""")
json.dump(C.ext.explain_last(details=True), sys.stdout, indent=4)

Snapshot Transactions#

snapshot transactions mode, which may help with metadata locking problems#
"""
Snapshot transactions
Explanations about locks: https://exasol.my.site.com/s/article/WAIT-FOR-COMMIT-on-SELECT-statement?language=en_US
"""

import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

# First connection, read first table, update second table
C1 = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    websocket_sslopt=config.websocket_sslopt,
)
C1.set_autocommit(False)

C1.execute("SELECT * FROM TAB1")
C1.execute("INSERT INTO TAB2 VALUES (1)")

# Second connection, update first table
C2 = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    websocket_sslopt=config.websocket_sslopt,
)
C2.set_autocommit(False)

C2.execute("INSERT INTO TAB1 VALUES(1)")
C2.commit()

# Third connection, read second table
C3 = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    snapshot_transactions=True,
    debug=True,
    websocket_sslopt=config.websocket_sslopt,
)

# Exasol locks on this query without snapshot transactions
stmt = C3.execute(
    "SELECT column_name, column_type FROM EXA_ALL_COLUMNS WHERE column_schema=CURRENT_SCHEMA AND column_table='TAB2'"
)
printer.pprint(stmt.fetchall())

UDF Script Output#

run query with UDF script and capture output (may not work on a local laptop)#
"""
Script output server
Exasol should be able to open connection to the host where current script is running
May not work on laptops due to firewall and network security restrictions
"""

import os
import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

is_travis = "TRAVIS" in os.environ

C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    query_timeout=5,
    # Custom parameters are required to make this example work in Travis context
    # 172.17.0.1 is an IP address of docker host in Linux
    udf_output_bind_address=("", 8580) if is_travis else None,
    udf_output_connect_address=("172.17.0.1", 8580) if is_travis else None,
    websocket_sslopt=config.websocket_sslopt,
)

# Normal script output from multiple VM's
stmt, log_files = C.execute_udf_output("""
    SELECT echo_java(user_id)
    FROM users
    GROUP BY CEIL(RANDOM() * 4)
""")

printer.pprint(stmt.fetchall())
printer.pprint(log_files)

print(log_files[0].read_text())

# No rows selected, no VM's started by Exasol, no log files created
# execute_udf_output should not hang in such case
stmt, log_files = C.execute_udf_output("""
    WITH cte_users AS (
        SELECT user_id
        FROM users
        ORDER BY null
        LIMIT 0
    )
    SELECT echo_java(user_id)
    FROM cte_users
    GROUP BY CEIL(RANDOM() * 4)
""")

printer.pprint(stmt.fetchall())
printer.pprint(log_files)

print(f"SELECTED {stmt.rowcount()} rows in {stmt.execution_time}s")

Class Extension#

extend core PyExasol classes to add custom logic#
"""
Extend core PyExasol classes, add custom logic
In this example we add print_session_id() custom method to all objects
"""

import collections
import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)


class CustomExaStatement(pyexasol.ExaStatement):
    def print_session_id(self):
        print(f"Statement session_id: {self.connection.session_id()}")


class CustomExaFormatter(pyexasol.ExaFormatter):
    def print_session_id(self):
        print(f"Formatter session_id: {self.connection.session_id()}")


class CustomExaLogger(pyexasol.ExaLogger):
    def print_session_id(self):
        print(f"Logger session_id: {self.connection.session_id()}")


class CustomExaExtension(pyexasol.ExaExtension):
    def print_session_id(self):
        print(f"Extension session_id: {self.connection.session_id()}")


class CustomExaMetaData(pyexasol.ExaMetaData):
    def print_session_id(self):
        print(f"MetaData session_id: {self.connection.session_id()}")


class CustomExaConnection(pyexasol.ExaConnection):
    # Set custom subclasses here
    cls_statement = CustomExaStatement
    cls_formatter = CustomExaFormatter
    cls_logger = CustomExaLogger
    cls_extension = CustomExaExtension
    cls_meta = CustomExaMetaData

    def __init__(self, **kwargs):
        if "custom_param" in kwargs:
            print(f"Custom connection parameter: {kwargs['custom_param']}")
            del kwargs["custom_param"]

        super().__init__(**kwargs)

    def execute(
        self, query: str, query_params: dict | None = None
    ) -> CustomExaStatement:
        return self.cls_statement(self, query, query_params)


custom_conn = CustomExaConnection(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    custom_param="test custom param!",
    websocket_sslopt=config.websocket_sslopt,
)

stmt = custom_conn.execute("SELECT * FROM users ORDER BY user_id LIMIT 5")

# Access overloaded objects
stmt.print_session_id()
custom_conn.format.print_session_id()
custom_conn.logger.print_session_id()
custom_conn.ext.print_session_id()
custom_conn.meta.print_session_id()

custom_conn.close()

print("Return result rows as named tuples")


class NamedTupleExaStatement(pyexasol.ExaStatement):
    def __next__(self):
        row = super().__next__()
        return self.cls_row(*row)

    def _init_result_set(self, res):
        super()._init_result_set(res)
        self.cls_row = collections.namedtuple("Row", self.col_names)


class NamedTupleExaConnection(pyexasol.ExaConnection):
    cls_statement = NamedTupleExaStatement

    def execute(
        self, query: str, query_params: dict | None = None
    ) -> NamedTupleExaStatement:
        return self.cls_statement(self, query, query_params)


named_tuple_conn = NamedTupleExaConnection(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    websocket_sslopt=config.websocket_sslopt,
)
named_tuple_stmt = named_tuple_conn.execute(
    "SELECT * FROM users ORDER BY user_id LIMIT 5"
)
print(named_tuple_stmt.fetchone())
print(named_tuple_stmt.fetchone())

named_tuple_conn.close()

Quoted Identifiers#

enable quoted identifiers for import_*, export_* and other relevant functions#
"""
Major cases when 'quote_ident' connection option takes effect
"""

import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)

# Basic connect
C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    quote_ident=True,
    websocket_sslopt=config.websocket_sslopt,
)

# Open schema
C.open_schema(config.schema)

# Export from table name with lower case characters
pd = C.export_to_pandas("camelCaseTable")
pd.info()

stmt = C.last_statement()
print(f"EXPORTED {stmt.rowcount()} rows in {stmt.execution_time}s")

# Export into table name with lower case characters
C.import_from_pandas(pd, "camelCaseTable")

stmt = C.last_statement()
print(f"IMPORTED {stmt.rowcount()} rows in {stmt.execution_time}s")

# Ext
cols = C.ext.get_columns("camelCaseTable")
printer.pprint(cols)

cols = C.ext.get_columns_sql(
    "SELECT * FROM {table_name!q}", {"table_name": "camelCaseTable"}
)
printer.pprint(cols)

cols = C.ext.get_columns((config.schema, "camelCaseTable"))
printer.pprint(cols)

cols = C.ext.get_sys_columns("camelCaseTable")
printer.pprint(cols)

Thread Safety#

built-in protection from accessing connection object from multiple threads simultaneously#
"""
Attempt to access connection object from multiple threads simultaneously
"""

import pprint
import threading
import time

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)


class QueryThread(threading.Thread):
    def __init__(self, connection):
        self.connection = connection
        super().__init__()

    def run(self):
        # Run heavy query
        try:
            self.connection.execute(
                "SELECT * FROM users a, users b, users c, payments d"
            )
        except pyexasol.ExaQueryAbortError as e:
            print(e.message)
        except pyexasol.ExaConcurrencyError as e:
            print(e.message)


# Basic connect
C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    websocket_sslopt=config.websocket_sslopt,
)

# Try to run multiple query threads in parallel
query_thread_1 = QueryThread(C)
query_thread_2 = QueryThread(C)

query_thread_1.start()
query_thread_2.start()

time.sleep(1)
C.abort_query()

query_thread_1.join()
query_thread_2.join()

DSN Parsing#

parsing of complex connection strings and catching relevant exceptions#
"""
Demonstration of DSN (Connection string) expansion and related exceptions
"""

import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)


C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    verbose_error=False,
    encryption=True,
    websocket_sslopt=config.websocket_sslopt,
)

print("IP range with custom port: ")
result = C._process_dsn("127.0.0.10..19:8564")
printer.pprint(sorted(result))

print("Multiple ranges with multiple ports and with default port at the end: ")
result = C._process_dsn("127.0.0.10..19:8564,127.0.0.20,localhost:8565,127.0.0.21..23")
printer.pprint(sorted(result))

print("Multiple ranges with fingerprint and port: ")
result = C._process_dsn("127.0.0.10..19/ABC,127.0.0.20,localhost/CDE:8564")
printer.pprint(sorted(result))

# Empty DSN
try:
    result = C._process_dsn(" ")
    printer.pprint(result)
except pyexasol.ExaConnectionDsnError as e:
    print(e)


# Invalid range
try:
    result = C._process_dsn("127.0.0.15..10")
    printer.pprint(result)
except pyexasol.ExaConnectionDsnError as e:
    print(e)

# Cannot resolve hostname
try:
    result = C._process_dsn("test1..5.zlan")
    printer.pprint(result)
except pyexasol.ExaConnectionDsnError as e:
    print(e)

# Hostname range with zero-padding
try:
    result = C._process_dsn("test01..20.zlan")
    printer.pprint(result)
except pyexasol.ExaConnectionDsnError as e:
    print(e)

HTTP Proxy#

connection via HTTP proxy#
"""
Open connection with HTTP proxy
"""

import pprint
import subprocess
import sys
import time

import examples._config as config
import pyexasol

PPROXY_COMPAT_BOOTSTRAP = (
    "import asyncio\n"
    "import sys\n"
    "asyncio.set_event_loop(asyncio.new_event_loop())\n"
    "from pproxy.server import main\n"
    "sys.exit(main())"
)


def _start_pproxy(proxy_url):
    if sys.version_info >= (3, 14):
        # Python 3.14 requires an explicit event loop before pproxy starts.
        command = [
            sys.executable,
            "-c",
            PPROXY_COMPAT_BOOTSTRAP,
            "-l",
            proxy_url,
            "--reuse",
        ]
    else:
        command = ["pproxy", "-l", proxy_url, "--reuse"]

    return subprocess.Popen(command)


printer = pprint.PrettyPrinter(indent=4, width=140)

# Simple HTTP proxy
pproxy = _start_pproxy("http://:8562/")
time.sleep(1)

C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    http_proxy="http://localhost:8562",
    websocket_sslopt=config.websocket_sslopt,
)

stmt = C.execute("SELECT * FROM users ORDER BY user_id LIMIT 5")
printer.pprint(stmt.fetchall())

C.close()
pproxy.terminate()


# HTTP proxy with auth
pproxy = _start_pproxy("http://:8562/#my_user:secret_pass")
time.sleep(1)

C = pyexasol.connect(
    dsn=config.dsn,
    user=config.user,
    password=config.password,
    schema=config.schema,
    http_proxy="http://my_user:secret_pass@localhost:8562",
    websocket_sslopt=config.websocket_sslopt,
)

stmt = C.execute("SELECT * FROM users ORDER BY user_id LIMIT 5")
printer.pprint(stmt.fetchall())

C.close()
pproxy.terminate()

Garbage Collection#

detect potential garbage collection problems due to cross-references#
"""
Ensure ExaConnection and ExaStatement objects are garbage collected properly
"""

import gc
import pprint

import examples._config as config
import pyexasol

printer = pprint.PrettyPrinter(indent=4, width=140)


class ExaStatementVerbose(pyexasol.ExaStatement):
    def __del__(self):
        print(
            f"ExaStatement session_id={self.connection.session_id()}, stmt_idx={self.stmt_idx} is about to be collected"
        )
        super().__del__()


class ExaConnectionVerbose(pyexasol.ExaConnection):
    cls_statement = ExaStatementVerbose

    def __del__(self):
        print(f"ExaConnection {self.session_id()} is about to be collected")
        super().__del__()


def run_test():
    C = ExaConnectionVerbose(
        dsn=config.dsn,
        user=config.user,
        password=config.password,
        schema=config.schema,
        debug=False,
        fetch_size_bytes=1024,
        websocket_sslopt=config.websocket_sslopt,
    )

    # Execute statement, read some data
    st = C.execute("SELECT * FROM users")
    st.fetchmany(5)

    # Execute another statement, no more references for the first statement
    st = C.execute("SELECT * FROM payments")
    st.fetchmany(5)

    del st
    del C

    print("Collect call 1 start")
    gc.collect()
    print("Collect call 1 finish")

    C = ExaConnectionVerbose(
        dsn=config.dsn,
        user=config.user,
        password=config.password,
        schema=config.schema,
        debug=False,
        fetch_size_bytes=1024,
        websocket_sslopt=config.websocket_sslopt,
    )

    st = C.execute("SELECT * FROM users")
    st.fetchmany(5)


run_test()

print("Collect call 2 start")
gc.collect()
print("Collect call 2 finish")

print("Finishing script, nothing should be collected beyond this point!")