ExaConnection#

class pyexasol.ExaConnection(dsn: str | None = None, user: str | None = None, password: str | None = None, schema: str = '', autocommit: bool = True, snapshot_transactions=None, connection_timeout=10, socket_timeout=30, query_timeout=0, compression: bool = False, encryption: bool = True, fetch_dict: bool = False, fetch_mapper=None, fetch_size_bytes=5242880, lower_ident: bool = False, quote_ident: bool = False, json_lib: str = 'json', verbose_error: bool = True, debug: bool = False, debug_logdir=None, udf_output_bind_address=None, udf_output_connect_address=None, udf_output_dir=None, http_proxy=None, resolve_hostnames: bool = True, client_name=None, client_version=None, client_os_username=None, protocol_version=3, websocket_sslopt: dict | None = None, access_token: str | None = None, refresh_token: str | None = None)[source]#

Bases: object

Warning

Threads may share the module, but not connections One connection may be used by different threads, just not at the same time pyexasol.ExaConnection.abort_query() is an exception, it is meant to be called from another thread

Note

It is advisable to use multiprocessing instead of threading and create a new connection in each sub-process

Public Attributes:
attr:

Read-only dict of attributes of current connection

login_info:

Read-only dict of login information returned by second response of LOGIN command

options:

Read-only dict of arguments passed to pyexasol.ExaConnection.connect()

__init__(dsn: str | None = None, user: str | None = None, password: str | None = None, schema: str = '', autocommit: bool = True, snapshot_transactions=None, connection_timeout=10, socket_timeout=30, query_timeout=0, compression: bool = False, encryption: bool = True, fetch_dict: bool = False, fetch_mapper=None, fetch_size_bytes=5242880, lower_ident: bool = False, quote_ident: bool = False, json_lib: str = 'json', verbose_error: bool = True, debug: bool = False, debug_logdir=None, udf_output_bind_address=None, udf_output_connect_address=None, udf_output_dir=None, http_proxy=None, resolve_hostnames: bool = True, client_name=None, client_version=None, client_os_username=None, protocol_version=3, websocket_sslopt: dict | None = None, access_token: str | None = None, refresh_token: str | None = None)[source]#

Exasol connection object

Parameters:
  • dsn – Connection string, same format as standard JDBC / ODBC drivers (e.g. 10.10.127.1..11:8564)

  • user – Username

  • password – Password

  • schema – Open schema after connection (Default: ‘’, no schema)

  • autocommit – Enable autocommit on connection (Default: True)

  • snapshot_transactions – Explicitly enable or disable snapshot transactions on connection (Default: None, database default)

  • connection_timeout – Socket timeout in seconds used to establish connection (Default: 10)

  • socket_timeout – Socket timeout in seconds used for requests after connection was established (Default: 30)

  • query_timeout – Maximum execution time of queries before automatic abort, in seconds (Default: 0, no timeout)

  • compression – Use zlib compression both for WebSocket and HTTP transport (Default: False)

  • encryption – Use SSL to encrypt client-server communications for WebSocket and HTTP transport (Default: True)

  • fetch_dict – Fetch result rows as dicts instead of tuples (Default: False)

  • fetch_mapper – Use custom mapper function to convert Exasol values into Python objects during fetching (Default: None)

  • fetch_size_bytes – Maximum size of data message for single fetch request in bytes (Default: 5Mb)

  • lower_ident – Automatically lowercase identifiers (table names, column names, etc.) returned from relevant functions (Default: False)

  • quote_ident – Add double quotes and escape identifiers passed to relevant functions (export_*, import_*, ext.*, etc.) (Default: False)

  • json_lib – Supported values: rapidjson, ujson, orjson, json (Default: json)

  • verbose_error – Display additional information when error occurs (Default: True)

  • debug – Output debug information for client-server communication and connection attempts to STDERR

  • debug_logdir – Store debug information into files in debug_logdir instead of outputting it to STDERR

  • udf_output_bind_address – Specific server_address to bind TCP server for UDF script output (default: (‘’, 0))

  • udf_output_connect_address – Specific SCRIPT_OUTPUT_ADDRESS value to connect from Exasol to UDF script output server (default: inherited from TCP server)

  • udf_output_dir – Directory to store captured UDF script output logs, split by <session_id>_<statement_id>/<vm_num>

  • http_proxy – HTTP proxy string in Linux http_proxy format (default: None)

  • resolve_hostnames – Explicitly resolve host names to IP addresses before connecting. Deactivating this will let the operating system resolve the host name (default: True).

  • client_name – Custom name of client application displayed in Exasol sessions tables (Default: PyExasol)

  • client_version – Custom version of client application (Default: pyexasol.__version__)

  • client_os_username – Custom OS username displayed in Exasol sessions table (Default: getpass.getuser())

  • protocol_version – Major WebSocket protocol version requested for connection (Default: pyexasol.PROTOCOL_V3)

  • websocket_sslopt – Set custom SSL options for WebSocket client (Default: None)

  • access_token – OpenID access token to use for the login process

  • refresh_token – OpenID refresh token to use for the login process

abort_query()[source]#

Abort running query

Warning

This function should be called from a separate thread and has no response. The response should be checked in the main thread which started the execution of the query.

There are three possible outcomes of calling this function:

  1. Query is aborted normally, connection remains active

  2. Query was stuck in a state which cannot be aborted, so Exasol has to terminate connection

  3. Query might be finished successfully before abort call had a chance to take effect

close(disconnect=True)[source]#

Closes connection to database.

Parameters:

disconnect – If true send optional “disconnect” command to free resources and close session on Exasol server side properly.

Note

Please note that “disconnect” should always be False when .close() is being called from .req()-like functions to prevent an infinite loop if websocket exception happens during handling of “disconnect” command.

cls_extension#

alias of ExaExtension

cls_formatter#

alias of ExaFormatter

cls_logger#

alias of ExaLogger

cls_meta#

alias of ExaMetaData

cls_statement#

alias of ExaStatement

commit()[source]#

Wrapper for query ‘COMMIT’

create_prepared_statement(sql: str) → ExaStatement[source]#

Create prepared statement

Parameters:

sql – SQL statement text, possibly with positional placeholders

Returns:

ExaStatement object

Examples

>>> con = ExaConnection(...)
>>> exa_stmt = con.create_prepared_statement(
...        sql="SELECT * FROM ? WHERE col1=?",
...)
>>> exa_stmt.execute_prepared( [('users', 'bar')] )
current_schema()[source]#

Get the name of the current schema.

Returns:

Name of currently opened schema. Returns an empty string if no schema was opened.

property exasol_db_version: Version | None#

Version of the Exasol database of the current session

The login information is returned by the second response of LOGIN command and calls this “releaseVersion”.

execute(query: str, query_params: dict | None = None) → ExaStatement[source]#

Execute SQL query with optional query formatting parameters

Parameters:
  • query – SQL query text, possibly with placeholders

  • query_params – Values for placeholders

Returns:

ExaStatement object

Examples

>>> con = ExaConnection(...)
>>> con.execute(
...        query="SELECT * FROM {table!i} WHERE col1={col1}",
...        query_params={'table': 'users', 'col1':'bar'}
...)
execute_sql_script(script: str) → list[ExaStatement][source]#

Execute a SQL script containing one or more statements.

The script is split into statements before execution. Semicolons inside string literals, quoted SQL identifiers, line comments, block comments, and Exasol script bodies do not terminate statements. Exasol script bodies are terminated by a standalone / line.

Statements are executed sequentially using execute(). The method returns a list with one pyexasol.ExaStatement for each executed statement, in execution order. If one statement fails, the original exception is raised and following statements are not executed.

Query parameters are intentionally not supported for SQL scripts. Use execute() for parameterized single statements.

execute_udf_output(query: str, query_params: dict | None = None)[source]#

Execute SQL query with UDF script, capture output

Note

Exasol should be able to open connection to the machine where current script is running. It is usually OK in the same data centre, but it is normally not working if you try to run this function on local laptop.

Parameters:
  • query – SQL query text, possibly with placeholders

  • query_params – Values for placeholders

Returns:

(1) instance of pyexasol.ExaStatement and (2) list of Path objects for script output log files.

Return type:

Return tuple with two elements

Attention

Exasol should be able to open connection to the machine where current script is running

Examples

>>> con = ExaConnection(...)
>>> stmt, output_files = con.execute_udf_output(
...        query="SELECT * FROM {table!i} WHERE col1={col1}",
...        query_params={'table': 'users', 'col1':'bar'}
...)
export_parallel(exa_address_list, query_or_table, query_params=None, export_params=None)[source]#

This function is part of Parallel API.

Parameters:
  • exa_address_list – List of ipaddr:port strings obtained from HTTP transport .address

  • query_or_table – SQL query or table for the export

  • query_params – Values for SQL query placeholders

  • export_params – Custom export_params for EXPORT query

Raises:

pydantic.ValidationError – Unknown keys or invalid values in export_params

Note

  • Init HTTP transport in child processes first using pyexasol.http_transport()

  • Get internal Exasol address from each child process using .address

  • Pass address strings to parent process, combine into single list and use it for export_parallel() call

export_to_callback(callback: Callable, dst, query_or_table: str | tuple[str, ...], query_params: dict | None = None, callback_params: dict | None = None, export_params: dict | None = None)[source]#

Export a large amount of data to a user-defined callback function

Parameters:
  • callback – Callback function

  • dst – (optional) Path to file or file-like object where data will be exported to

  • query_or_table –

    Source from which to export data. Can be one of:

    • tuple[str, ...]: fully qualified table identifier, such as ("SCHEMA", "TABLE"). Quoted table names must be fully qualified using this tuple pattern.

    • str: if lacks non-trailing space, it is treated like a table identifier. Otherwise, it is treated like a query.

  • query_params – Values for SQL query placeholders

  • callback_params – Dictionary with additional parameters for callback function

  • export_params – Custom export_params for EXPORT query

Returns:

result of callback function

Raises:
  • TypeError – callback argument is not Callable

  • pydantic.ValidationError – Invalid values from export_params

  • ExaExportError – one or more exceptions occurred when executing the callback function

Warning

  • This function may run out of memory

Examples

>>> cb = lambda args: print(args)
>>> con = ExaConnection(...)
>>> con.export_to_callback(
...    callback=cb,
...    query_or_table="SELECT * FROM table"
... )
export_to_file(dst, query_or_table: str | tuple[str, ...], query_params: dict | None = None, export_params: dict | None = None)[source]#

Export large amount of data from Exasol to file or file-like object using fast HTTP transport.

Note

File must be opened in binary mode.

Parameters:
  • dst – Path to file or file-like object where data will be exported to

  • query_or_table –

    Source from which to export data. Can be one of:

    • tuple[str, ...]: fully qualified table identifier, such as ("SCHEMA", "TABLE"). Quoted table names must be fully qualified using this tuple pattern.

    • str: if lacks non-trailing space, it is treated like a table identifier. Otherwise, it is treated like a query.

  • query_params – Values for SQL query placeholders

  • export_params – Custom export_params for EXPORT query

Examples

>>> con = ExaConnection(...)
>>> with open('/tmp/file.csv', 'wb') as f:
...     con.export_to_file(
...         dst=f,
...         query_or_table="SELECT * FROM table"
...     )
export_to_list(query_or_table: str | tuple[str, ...], query_params: dict | None = None, export_params: dict | None = None) → list[source]#

Export large amount of data from Exasol to basic Python list using fast HTTP transport.

Parameters:
  • query_or_table –

    Source from which to export data. Can be one of:

    • tuple[str, ...]: fully qualified table identifier, such as ("SCHEMA", "TABLE"). Quoted table names must be fully qualified using this tuple pattern.

    • str: if lacks non-trailing space, it is treated like a table identifier. Otherwise, it is treated like a query.

  • query_params – Values for SQL query placeholders

  • export_params – Custom export_params for EXPORT query

Returns:

list of tuples

Warning

  • This function may run out of memory

Examples

>>> con = ExaConnection(...)
>>> myresult = con.export_to_list(
...    query_or_table="SELECT * FROM table"
... )
export_to_pandas(query_or_table: str | tuple[str, ...], query_params: dict | None = None, callback_params: dict | None = None, export_params: dict | None = None) → pandas.DataFrame[source]#

Export large amount of data from Exasol to pandas.DataFrame.

Parameters:
  • query_or_table –

    Source from which to export data. Can be one of:

    • tuple[str, ...]: fully qualified table identifier, such as ("SCHEMA", "TABLE"). Quoted table names must be fully qualified using this tuple pattern.

    • str: if lacks non-trailing space, it is treated like a table identifier. Otherwise, it is treated like a query.

  • query_params – Values for SQL query placeholders

  • callback_params – Dictionary with additional parameters for callback function pandas.read_csv

  • export_params – Custom export_params for EXPORT query

Returns:

instance of pandas.DataFrame

Warning

  • This function may run out of memory

Examples

>>> con = ExaConnection(...)
>>> myresult = con.export_to_pandas(
...    query_or_table="SELECT * FROM table"
... )
export_to_parquet(dst: Path | str, query_or_table: str | tuple[str, ...], query_params: dict | None = None, callback_params: dict | None = None, export_params: dict | None = None)[source]#

Export large amounts of data from Exasol to local parquet file(s).

Parameters:
  • dst –

    Local path to directory for exporting files. Can be either a Path or str. The default behavior, which can be changed via callback_params, is that the specified directory should be empty. If that is not the case, one of these exceptions may be thrown:

    ValueError

    ’<dst>’ exists and is not a directory

    ValueError

    ’<dst>’ contains existing files and callback_params[‘existing_data_behavior’] is not one of these values: (“overwrite_or_ignore”, “delete_matching”).

    pyarrow.lib.ArrowInvalid:

    Could not write to <dst> Parquet Export from Exasol via Python Container/parquet as the directory is not empty and existing_data_behavior is to error.

    ValueError:

    I/O operation on closed file

    DB error message:

    ETL-5106: Following error occured while writing data to external connection [https://172.0.0.1:8653/000.csv failed after 200009 bytes. [OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 0],[56],[Failure when receiving data from the peer]] (Session: XXXXX)

    The ValueError exceptions would come from a check we provide via pyexasol.callback.check_export_to_parquet_directory_setting(). The purpose of calling this check is to detect issues before executing code within the callback pattern, which uses three threads. If a user has a different issue than we anticipated, it’s possible one of the other three exceptions is tossed for this, as discussed on Importing and Exporting Data.

  • query_or_table –

    Source from which to export data. Can be one of:

    • tuple[str, ...]: fully qualified table identifier, such as ("SCHEMA", "TABLE"). Quoted table names must be fully qualified using this tuple pattern.

    • str: if lacks non-trailing space, it is treated like a table identifier. Otherwise, it is treated like a query.

  • query_params – Values for SQL query placeholders

  • callback_params –

    Dictionary with additional parameters for callback function pyarrow.dataset.write_dataset. Some important defaults to note are:

    existing_data_behavior

    Set to error, which requires that the specified dst not contain any files or an exception will be thrown

    max_rows_per_file

    Set to 0, which means that all rows will be written to 1 file. If max_rows_per_file is altered, ensure that max_rows_per_group is set to a value less than or equal to the value of max_rows_per_file.

    use_threads

    Set to True and preserve_order is set to False. This means that the writing of multiple files will be done in parallel and that the order is not guaranteed to be preserved.

  • export_params – Custom export_params for EXPORT query

export_to_polars(query_or_table: str | tuple[str, ...], query_params: dict | None = None, callback_params: dict | None = None, export_params: dict | None = None) → polars.DataFrame[source]#

Export large amount of data from Exasol to polars.DataFrame.

Parameters:
  • query_or_table –

    Source from which to export data. Can be one of:

    • tuple[str, ...]: fully qualified table identifier, such as ("SCHEMA", "TABLE"). Quoted table names must be fully qualified using this tuple pattern.

    • str: if lacks non-trailing space, it is treated like a table identifier. Otherwise, it is treated like a query.

  • query_params – Values for SQL query placeholders

  • callback_params – Dictionary with additional parameters for callback function polars.read_csv

  • export_params – Custom export_params for EXPORT query

Returns:

instance of polars.DataFrame

Warning

  • This function may run out of memory

Examples

>>> con = ExaConnection(...)
>>> df = con.export_to_polars(
...    query_or_table="SELECT * FROM table"
... )
get_attr()[source]#
get_nodes(pool_size=None)[source]#

List of currently active Exasol nodes which is normally used for Parallel

Parameters:

pool_size – Return list of specific size.

Returns:

list of dictionaries describing active Exasol nodes

Note

Format: {'ipaddr': <ip_address>, 'port': <port>, 'idx': <incremental index of returned node>}

  • If pool_size is bigger than number of nodes, list will wrap around and nodes will repeat with different ‘idx’

  • If pool_size is omitted, return every active node once

  • It is useful to balance workload for parallel IMPORT and EXPORT Exasol shuffles list for every connection

  • Exasol shuffles list for every connection.

import_from_callback(callback: Callable, src, table: str | tuple[str, ...], callback_params: dict | None = None, import_params: dict | None = None)[source]#

Import a large amount of data from a user-defined callback function.

Parameters:
  • callback – Callback function

  • src – Source for the callback function

  • table –

    Destination table for IMPORT. Can be one of:

    • str: table identifier

    • tuple[str, ...]: schema-qualified table identifier, such as ("SCHEMA", "TABLE")

  • callback_params – Dictionary with additional parameters for callback function

  • import_params – Custom import_params for IMPORT query

Raises:
  • TypeError – callback argument is not Callable

  • pydantic.ValidationError – Invalid values from import_params

import_from_file(src, table: str | tuple[str, ...], import_params: dict | None = None)[source]#

Import a large amount of data from a file or file-like object.

Parameters:
  • src – Source file or file-like object. Must be either a file-path, or a binary stream, i.e. a file opened in binary mode.

  • table –

    Destination table for IMPORT. Can be one of:

    • str: table identifier

    • tuple[str, ...]: schema-qualified table identifier, such as ("SCHEMA", "TABLE")

  • import_params – Custom import_params for IMPORT query

Note

File must be opened in binary mode.

row_separator is only sent when you set it, so the database applies its own default of LF. For files with CRLF line endings, as written by Python’s csv module, pass import_params={"row_separator": "CRLF"}, otherwise the carriage return stays in the last column of every row or the import fails with ETL-2105 when the last column is quoted. Alternatively, write the file with LF line endings.

import_from_iterable(src: Iterable, table: str | tuple[str, ...], import_params: dict | None = None)[source]#

Import a large amount of data from an iterable Python object.

Parameters:
  • src – Source object implementing __iter__. Iterator must return tuples of values.

  • table –

    Destination table for IMPORT. Can be one of:

    • str: table identifier

    • tuple[str, ...]: schema-qualified table identifier, such as ("SCHEMA", "TABLE")

  • import_params – Custom import_params for IMPORT query

import_from_pandas(src: pandas.DataFrame, table: str | tuple[str, ...], callback_params: dict | None = None, import_params: dict | None = None)[source]#

Import a large amount of data from pandas.DataFrame.

Parameters:
  • src – Source pandas.DataFrame instance

  • table –

    Destination table for IMPORT. Can be one of:

    • str: table identifier

    • tuple[str, ...]: schema-qualified table identifier, such as ("SCHEMA", "TABLE")

  • callback_params – Dictionary with additional parameters for callback function pandas.DataFrame.to_csv

  • import_params – Custom import_params for IMPORT query

import_from_parquet(source: list[Path] | Path | str, table: str | tuple[str, ...], callback_params: dict | None = None, import_params: dict | None = None, native: bool = True)[source]#

Import a large amount of data from local parquet file(s).

Exasol 2026.1.0 and newer use the native Parquet import, older versions use the callback-based import. Pass native=False to force the callback-based import. See the note at the end for the differences.

Parameters:
  • source –

    Local filepath specification(s) to process. Can be one of:

    • list[pathlib.Path]: list of specific files

    • pathlib.Path: can be either a file or directory. If it’s a directory, all files matching this pattern *.parquet will be processed.

    • str: representing a filepath which already contains a glob pattern (e.g., /local_dir/*.parquet)

  • table –

    Destination table for IMPORT. Can be one of:

    • str: table identifier

    • tuple[str, ...]: schema-qualified table identifier, such as ("SCHEMA", "TABLE")

  • callback_params –

    Dict with additional parameters.

    • Callback-based import: Dict with additional parameters for callback function parquet.ParquetFile.iter_batches

    • Native import: only max_files_per_batch is supported (default 1), see the note below. Any other key raises pydantic.ValidationError.

  • import_params –

    Custom parameters for IMPORT query. They are the import_params of:

    • Callback-based import: pyexasol.query_builders.csv.builders.ImportBuilder

    • Native Parquet import: pyexasol.query_builders.parquet.builders.ImportBuilder

  • native – If False, always use the callback-based import. Defaults to True (use the native import when the database supports it).

Note

The native import (Exasol 2026.1.0 and newer) differs from the callback-based import in the following ways:

  • No type conversion: The Parquet column types must match the table. For example, a Parquet double cannot be imported into a DECIMAL column. The callback-based import sends CSV, so Exasol converts the values.

  • Batches: Exasol opens one connection per file, so the files are split into batches of at most max_files_per_batch files (see callback_params). A batch is imported in parallel by one IMPORT statement, the batches in sequence.

  • Transaction: If autocommit is on and there is more than one batch, all batches run in one transaction. It is committed after the last batch, or rolled back if any batch fails, and autocommit is restored afterward. A single batch is one IMPORT statement, which is atomic anyway, so no transaction is started and last_statement() still returns the IMPORT. If autocommit is off, nothing is committed or rolled back, so you control the transaction: if a later batch fails, the earlier batches remain in it.

  • last_statement(): The callback-based import runs one IMPORT, so last_statement() gives the total rowcount() and execution_time. The native import only does this for a single batch. With several batches, it returns the COMMIT (autocommit on, rowcount() is 0) or the last batch’s IMPORT (autocommit off), so do not rely on it for the number of imported rows. Count the rows in the table instead.

import_from_polars(src: polars.LazyFrame | polars.DataFrame, table: str | tuple[str, ...], callback_params: dict | None = None, import_params: dict | None = None)[source]#

Import a large amount of data from polars.DataFrame or polars.LazyFrame.

Parameters:
  • src – Source polars.DataFrame or polars.LazyFrame instance

  • table –

    Destination table for IMPORT. Can be one of:

    • str: table identifier

    • tuple[str, ...]: schema-qualified table identifier, such as ("SCHEMA", "TABLE")

  • callback_params – Dictionary with additional parameters for callback function polars.DataFrame.write_csv

  • import_params – Custom import_params for IMPORT query

import_parallel(exa_address_list, table, import_params=None)[source]#

This function is part of Parallel API.

Parameters:
  • exa_address_list – List of ipaddr:port strings obtained from HTTP transport .address

  • table – Table to import to

  • import_params – Custom import_params for IMPORT query

Raises:

pydantic.ValidationError – Unknown keys or invalid values in import_params

Note

  • Init HTTP transport in child processes first using pyexasol.http_transport()

  • Get internal Exasol address from each child process using .address

  • Pass address strings to parent process, combine into single list and use it for import_parallel() call

last_statement() → ExaStatement[source]#

Last created statement object

Returns:

last created statement

Return type:

ExaStatement

Note

It is mainly used for HTTP transport to access internal IMPORT / EXPORT query, measure execution time and number of rows

Tip

It is useful while working with export_* and import_* functions normally returning result of callback function instead of statement object.

open_schema(schema)[source]#

Wrapper for OPEN SCHEMA

Parameters:

schema – Schema name

protocol_version() → int[source]#

Actual protocol version used by the established connection

Returns:

0 if connection was not established yet (e.g. due to exception handling), otherwise protocol version as int

Warning

Actual Protocol version might be downgraded from requested protocol version if Exasol server does not support it

Note

The actual protocol version may be lower than the requested protocol version defined by the protocol_version connection option. For further details, refer to WebSocket Protocol Version.

req(req)[source]#

Send WebSocket request and wait for response

rollback()[source]#

Wrapper for query ‘ROLLBACK’

session_id() → str[source]#

Session id of current session

Returns:

Unique SESSION_ID of the current session as string

set_attr(new_attr)[source]#
set_autocommit(val: bool) → None[source]#

Set autocommit mode.

Parameters:

val – Set False to execute following statements in transaction. Set True to get back to automatic COMMIT after each statement.

Note

Autocommit is True by default because Exasol has to commit indexes and statistics objects even for pure SELECT statements. Lack of default COMMIT may lead to serious performance degradation.

set_query_timeout(val)[source]#

Set the maximum time in seconds for which a query can run before Exasol kills it automatically.

Parameters:

val – Timeout value in seconds. Set value 0 to disable timeout.

Note

It is highly recommended to set timeout for UDF scripts to avoid potential infinite loops and very long transactions.

threadsafety = 1#