tableauhyperapi reference

tableauhyperapi - a Hyper client library.

This library allows spawning a local Hyper server instance, connecting to a Hyper server, running queries and commands, and writing data into database tables.

tableauhyperapi classes are implemented in submodules of the tableauhyperapi package, however those submodules are considered a private implementation detail, and there are no stability guarantees for them. Only symbols exported from the top-level tableauhyperapi package constitute the stable public API.

Sample usage

Create a database and push some data into it:

from tableauhyperapi import HyperProcess, Connection, TableDefinition, SqlType, Telemetry, Inserter, CreateMode

# Start a new private local Hyper instance
with HyperProcess(Telemetry.SEND_USAGE_DATA_TO_TABLEAU, 'myapp') as hyper:
    # Create the extract, replace it if it already exists
    with Connection(hyper.endpoint, 'mydb.hyper', CreateMode.CREATE_AND_REPLACE) as connection:
        schema = TableDefinition('foo', [
            TableDefinition.Column('a', SqlType.text()),
            TableDefinition.Column('b', SqlType.big_int()),
        ])
        connection.catalog.create_table(schema)
        with Inserter(connection, schema) as inserter:
            inserter.add_rows([
                ['x', 1],
                ['y', 2],
            ])
            inserter.execute()

Connect to an existing extract and append data to a table in it:

with Connection(hyper.endpoint, 'mydb.hyper') as connection:
    with Inserter(connection, 'foo') as inserter:
        inserter.add_row(['z', 3])
        inserter.execute()

Run some queries:

with connection.execute_query('SELECT * FROM foo') as result:
    rows = list(result)
    assert sorted(rows) == [['x', 1], ['y', 2], ['z', 3]]

    top_a = connection.execute_scalar_query('SELECT MAX(b) FROM foo')
    assert top_a == 3

    connection.execute_command('DROP TABLE foo')

API Reference

tableauhyperapi.HyperException

An exception raised by the Hyper API.

tableauhyperapi.HyperProcess

Starts a local Hyper server instance managed by the library.

tableauhyperapi.Connection

Connects to a Hyper server.

tableauhyperapi.Endpoint

A network endpoint to which a connection can be established.

tableauhyperapi.Catalog

The class which is responsible for querying and manipulating metadata.

tableauhyperapi.Inserter

An object which is used to insert data into a table.

tableauhyperapi.TableDefinition

A SQL table definition.

tableauhyperapi.Persistence

Persistence type of a table.

tableauhyperapi.Result

An object which is used to read query results.

tableauhyperapi.ResultSchema

The schema of a query result.

tableauhyperapi.TypeTag

Constants which represent Hyper data types.

tableauhyperapi.SqlType

An object which represents a column type - type tag and optional type-specific modifiers.

tableauhyperapi.Name

An object which represents a SQL object name.

tableauhyperapi.DatabaseName

An escaped Database Name

tableauhyperapi.SchemaName

An escaped and potentially qualified Schema Name.

tableauhyperapi.TableName

An escaped and potentially qualified TableName.

tableauhyperapi.Date

A Hyper DATE value - year, month, and day.

tableauhyperapi.Timestamp

A Hyper timestamp - date and time of day.

tableauhyperapi.Interval

A Hyper INTERVAL.

tableauhyperapi.HyperServiceVersion

A Hyper Service version number of the form ‘major.minor’.

exception tableauhyperapi.HyperException(context_id: tableauhyperapi.ContextId, main_message: Optional[str] = None, hint: Optional[str] = None, message: Optional[str] = None, hint_message: Optional[str] = None)[source]

Bases: Exception

An exception raised by the Hyper API. Note that error messages may change in the future versions of the library.

context_id = None

A context ID. Each throw expression has a unique context id that is stored in the thrown error.

hint = None

A possible hint on how to fix the error.

hint_message

A possible hint on how to fix the error.

Warning

Deprecated: Use hint

main_message = None

The main message of this exception.

message

The main message of this exception.

Warning

Deprecated: Use main_message

class tableauhyperapi.HyperProcess(telemetry: tableauhyperapi.Telemetry, user_agent: str = '', hyper_path: Union[str, pathlib.PurePath] = None, parameters: Mapping[str, str] = None)[source]

Bases: object

Starts a local Hyper server instance managed by the library.

Parameters
  • telemetryTelemetry constant which defines whether telemetry should be enabled.

  • user_agent – arbitrary string which identifies the application. May be left unspecified.

  • hyper_path – path to the directory which contains hyperd executable. If not specified, the library will try to locate it in pre-determined places.

  • parameters – Optional dictionary of parameters for starting the Hyper process. The available parameters are documented in the Tableau Hyper documentation, chapter “Process Settings”.

Example usage:

with HyperProcess(Telemetry.SEND_USAGE_DATA_TO_TABLEAU, 'myapp') as hyper:
    with Connection(hyper.endpoint, 'mydb.hyper', CreateMode.CREATE) as connection:
        # ...
        pass

The server must be stopped either implicitly by a with statement, or explicitly by the close() or shutdown() method. Even if it’s not stopped, the server will be terminated when the process exits. You cannot use tableauhyperapi to start the server and let it stay running after the script exits.

close()[source]

Stops the server, ignoring possible errors. This is called automatically when with statement is used. Use shutdown() instead of close() to get the shutdown errors as a HyperException.

endpoint

Endpoint of this process to connect to.

is_open

Returns true if the server has not been shut down yet.

shutdown(timeout_ms: int = -1)[source]

Shuts down the Hyper server.

If timeout_ms > 0ms, wait for Hyper to shut down gracefully. If the process is still running after a timeout of timeout_ms milliseconds, forcefully terminate the process and raise an exception.

If timeout_ms < 0ms, wait indefinitely for Hyper to shut down.

If timeout_ms == 0ms, immediately terminate Hyper forcefully. Does not throw if the process already exited with a non-zero exit code.

A HyperException is raised if there was an error stopping the process, if the process was forcefully killed after the timeout, or if the process already exited with a non-zero exit code.

Parameters

timeout_ms – timeout in milliseconds.

class tableauhyperapi.Telemetry[source]

Bases: enum.Enum

Constants which define whether usage data is sent to Tableau to improve the Hyper API.

DO_NOT_SEND_USAGE_DATA_TO_TABLEAU = 0

Do not share usage data with Tableau.

SEND_USAGE_DATA_TO_TABLEAU = 1

Help us improve the Hyper API by sharing usage data with Tableau.

class tableauhyperapi.Connection(endpoint: tableauhyperapi.Endpoint, database: Union[str, pathlib.PurePath, None] = None, create_mode: Optional[tableauhyperapi.CreateMode] = <CreateMode.NONE: 0>, parameters: Optional[Mapping[str, str]] = None)[source]

Bases: object

Connects to a Hyper server.

Parameters

If the database is not specified, then it connects to the main database. This is useful to create and delete databases. Note that the main database gets deleted once the HyperProcess gets closed.

No methods of this class are thread-safe, except cancel(), which can be called from a different thread.

# Connect and create the database. If it already exists, replace it.
with Connection(hyper.endpoint, 'mydb.hyper', CreateMode.CREATE_AND_REPLACE) as connection:
    schema = TableDefinition('table', [
        TableDefinition.Column('text', SqlType.text()),
        TableDefinition.Column('int', SqlType.int()),
    ])
    connection.catalog.create_table(schema)
cancel()[source]

Cancels the current SQL command or query of this connection (if any). This method may be safely called from any thread. After this method was called, the current SQL command or query may fail with a cancellation error at any point during its execution. However, there are no guarantees if and when it will fail.

catalog

Gets the Catalog for this connection.

close()[source]

Closes the connection. Note that this has no effect if there is an active result or data inserter. These need to be closed before the connection to the server will be actually dropped.

execute_command(command) → Optional[int][source]

Executes a SQL statement and returns the affected row count if the statement has one.

Parameters

command – SQL statement to execute.

Returns

Count of affected rows if available, None otherwise.

execute_list_query(query, text_as_bytes=False) → List[List[Union[bool, bytearray, bytes, datetime.time, tableauhyperapi.Date, decimal.Decimal, float, int, tableauhyperapi.Interval, str, tableauhyperapi.Timestamp, None]]][source]

Executes a SQL query and returns the result as list of rows of data, each represented by a list of objects.

Parameters
  • query – SQL query to execute.

  • text_as_bytes – optional, if True then string values read from the database will be returned as UTF-8-encoded bytearray objects. By default string values are returned as str objects.

Returns

A list of rows, each represented by a list of objects. See TypeTag documentation for how database values are represented by Python objects.

execute_query(query, text_as_bytes=False) → tableauhyperapi.Result[source]

Executes a SQL query and returns the result as a Result object.

Parameters
  • query – SQL query to execute.

  • text_as_bytes – optional, if True then string values read from the database will be returned as UTF-8-encoded bytearray objects. By default string values are returned as str objects.

Returns

A Result instance. Use this method in a with statement to automatically close the result when done reading from it, or call its close() method. No queries can be executed or tables created/opened while the result is open.

execute_scalar_query(query, text_as_bytes=False) → Union[bool, bytearray, bytes, datetime.time, tableauhyperapi.Date, decimal.Decimal, float, int, tableauhyperapi.Interval, str, tableauhyperapi.Timestamp, None][source]

Executes a scalar query, i.e. a query that returns exactly one row with one column, and returns the value from the result.

Parameters
  • query – SQL query to execute.

  • text_as_bytes – optional, if True then a string value read from the database will be returned as UTF-8-encoded bytearray objects. By default string values are returned as str objects.

Returns

the value from the result. A NULL database value is returned as None. See TypeTag documentation for how database values are represented by Python objects.

hyper_service_version() → tableauhyperapi.HyperServiceVersion[source]

Returns the Hyper Service version of this connection

Returns

The Hyper Service version of this connection

is_capability_active(capability_flag: str) → bool[source]

Returns true if the capability flag is active on this connection.

Parameters

capability_flag – The capability flag to check. It is prefixed with capability_.

Returns

true if the capability flag is active on this connection.

is_open

Returns True if the connection has not been closed yet.

is_ready

Checks whether the connection is ready, i.e., it is not processing a query. An open Inserter or Result keeps the connection busy.

static query_supported_hyper_service_version_range(endpoint: tableauhyperapi.Endpoint) → List[tableauhyperapi.HyperServiceVersion][source]
Connects to the Hyper endpoint and determines which Hyper Service version numbers are common

between the Hyper API and the Hyper server.

Param

endpoint Endpoint to connect to.

Returns

List of Hyper Service versions that are supported by both this Hyper API and the endpoint.

class tableauhyperapi.Endpoint(connection_descriptor: str, user_agent: str)[source]

Bases: object

A network endpoint to which a connection can be established. Use HyperProcess.endpoint to get the endpoint to connect to the Hyper process.

connection_descriptor

The string representation of the endpoint.

user_agent

The user agent.

class tableauhyperapi.CreateMode[source]

Bases: enum.Enum

Constants which define what happens when connecting to a database depending on whether it already exists.

CREATE = 1

Create the database. Method will fail if the database already exists.

CREATE_AND_REPLACE = 3

Create the database. If it already exists, drop the old one first.

CREATE_IF_NOT_EXISTS = 2

Create the database if it does not exist.

NONE = 0

Do not create the database. Method will fail if database does not exist.

class tableauhyperapi.Catalog(connection: tableauhyperapi.Connection)[source]

Bases: object

The class which is responsible for querying and manipulating metadata.

Do not create instances of this class, use Connection.catalog instead.

attach_database(database_path: Union[str, pathlib.PurePath], alias: Union[str, tableauhyperapi.Name, tableauhyperapi.DatabaseName, None] = None)[source]

Attaches a database to the underlying connection.

connection

Gets the underlying connection.

create_database(database_path: Union[str, pathlib.PurePath])[source]

Creates a new database at the given path. The file must not already exist. It does not attach the database to the current connection.

Parameters

database_path – path to the database file.

create_database_if_not_exists(database_path: Union[str, pathlib.PurePath])[source]

Creates a new database at the given path if it does not already exist, otherwise does nothing. It does not attach the database to the current connection.

Note: This method raises an exception if a file that is not a hyper database exists at the given path.

Parameters

database_path – path to the database file.

create_schema(schema: Union[str, tableauhyperapi.Name, tableauhyperapi.SchemaName])[source]

Creates a new schema with the given name. The schema must not already exist.

Parameters

schema – the name of the schema.

create_schema_if_not_exists(schema: Union[str, tableauhyperapi.Name, tableauhyperapi.SchemaName])[source]

Creates a new schema with the given name if it does not already exist, otherwise does nothing.

Parameters

schema – the name of the schema.

create_table(table_definition: tableauhyperapi.TableDefinition)[source]

Creates a table. Raise an exception if the table already exists.

Parameters

table_definition – the table definition.

create_table_if_not_exists(table_definition: tableauhyperapi.TableDefinition)[source]

Creates a table if it does not already exist, otherwise does nothing.

Parameters

table_definition – the table definition.

detach_all_databases()[source]

Detaches all databases from the underlying connection.

detach_database(alias: Union[str, tableauhyperapi.Name, tableauhyperapi.DatabaseName])[source]

Detaches a database from the underlying connection.

drop_database(database_path: Union[str, pathlib.PurePath])[source]

Drops a database file. Raise an exception if the database does not exist.

drop_database_if_exists(database_path: Union[str, pathlib.PurePath])[source]

Drops a database file if it exists, otherwise does nothing.

get_schema_names(database: Union[tableauhyperapi.DatabaseName, tableauhyperapi.Name, str] = None) → List[tableauhyperapi.SchemaName][source]

Gets the names of all schemas of the database specified by the database name, or of the first database in the search path if the name is not specified.

get_table_definition(name: Union[tableauhyperapi.TableName, tableauhyperapi.Name, str]) → tableauhyperapi.TableDefinition[source]

Gets a table definition. Raises an exception if the table does not exist.

get_table_names(schema: Union[tableauhyperapi.SchemaName, tableauhyperapi.Name, str]) → List[tableauhyperapi.TableName][source]

Gets the names of all tables in the specified schema.

has_table(name: Union[tableauhyperapi.TableName, tableauhyperapi.Name, str]) → bool[source]

Does a table with this name exist?

class tableauhyperapi.Result(text_as_bytes: bool, connection: tableauhyperapi.Connection, result_cdata)[source]

Bases: object

An object which is used to read query results.

A Result implements the iterator protocol, so it can be used as follows:

with connection.execute_query('SELECT * FROM foo') as result:
    for row in result:
        print(row)
['a', 1]
['b', 2]

This is equivalent to the following:

with connection.execute_query('SELECT * FROM foo') as result:
    while result.next_row():
        row = result.get_values()
        print(row)
['a', 1]
['b', 2]

Alternatively, one can use get_value() to retrieve individual row values:

with connection.execute_query('SELECT * FROM foo') as result:
    while result.next_row():
        value = result.get_value(0)
        print(value)
a
b

NULL database values are represented by None. See TypeTag documentation for how Hyper data types map to Python types.

The Result constructor may not be used directly, use Connection.execute_query.

affected_row_count

Gets the affected row count, if the statement had any.

close()[source]

Closes the result. Normally this is called automatically by with statement. Also, result is automatically closed when all rows have been read from it.

connection

Gets the underlying connection.

get_value(column_index: int) → object[source]

Gets the value at the given column index in the current row. This MUST only be called if next_row() returned True.

Parameters

column_index – the column index.

Returns

the value as the corresponding python object if it is non-NULL, or None otherwise. See TypeTag for how Hyper data types map to Python types.

get_values() → List[Union[bool, bytearray, bytes, datetime.time, tableauhyperapi.Date, decimal.Decimal, float, int, tableauhyperapi.Interval, str, tableauhyperapi.Timestamp, None]][source]

Gets the values in the current row. This MUST only be called if next_row() returned True.

Returns

the row values as a list of objects. NULL is represented by None, see TypeTag for how Hyper data types map to Python types.

is_open

Returns True if the result has not been closed yet. Note that reading all rows of data automatically closes the result object.

next_row() → bool[source]

Fetches the next row.

Returns

True if there is data to read, False otherwise.

Note: if this method returns False, then the result is closed.

schema

Gets the result schema.

class tableauhyperapi.ResultSchema(columns: Iterable[tableauhyperapi.ResultSchema.Column])[source]

Bases: object

The schema of a query result. It consists of columns, which have a type and a name.

class Column(name: Union[tableauhyperapi.Name, str], type: tableauhyperapi.SqlType)[source]

Bases: object

A result column.

name

The name of the column.

type

The type of the column.

column_count

The column count.

columns

The list of the columns.

get_column(position: int) → tableauhyperapi.ResultSchema.Column[source]

Gets the column at the given position.

Parameters

position – column position, in the range from 0 to column_count-1.

Returns

the column at the given index.

get_column_by_name(name: Union[tableauhyperapi.Name, str]) → Optional[tableauhyperapi.ResultSchema.Column][source]

Gets the column with the given name, if it exists.

Parameters

name – the column name.

Returns

the column with the given name, or None if it does not exist.

get_column_position_by_name(name: Union[str, tableauhyperapi.Name]) → Optional[int][source]

Gets the position of the column with the given name, if it exists.

Parameters

name – the column name.

Returns

the column position, or None if it does not exist.

class tableauhyperapi.Inserter(connection: tableauhyperapi.Connection, arg: Union[str, tableauhyperapi.Name, tableauhyperapi.TableName, tableauhyperapi.TableDefinition], columns: Iterable[Union[str, tableauhyperapi.Inserter.ColumnMapping]] = None, *, inserter_definition: Iterable[tableauhyperapi.TableDefinition.Column] = None)[source]

Bases: object

An object which is used to insert data into a table.

Parameters
  • connection – the connection to use.

  • arg – either the table name or the definition of the table to insert data into.

  • columns – The set of columns in which to insert. The columns have to exist in the table. When not None, Columns not present in columns will be set to their default value. columns is a Iterable of either string or Inserter.ColumnMapping A columnMapping can optionally contain a valid SQL expression. The SQL expression specified for the column is used to transform or compute values on the fly during insertion. The SQL expression can depend on columns that exist in the table. The SQL expression can also depend on values or columns that do not exist in the table, but must be specified in the inserter_dfinition.

  • inserter_definition – The definition of columns to which values are provided. inserter_definition is a keyword-only parameter required only when columns is not None The column definition for all the columns without SQL expression must be specified in inserter_definition. For a column without SQL expression, the column definition provided in inserter_definition must match the actual definition of the column in the table.

Note

SQL expression provided during insertion are used without any modification during insertion and hence vulnerable to SQL injection attacks. Applications should prevent end-users from providing expressions directly during insertion

Sample usage:

with Inserter(connection, 'foo') as inserter:
    inserter.add_row(['a', 1])
    inserter.add_row(['b', 2])
    inserter.execute()
class ColumnMapping(column_name: Union[tableauhyperapi.Name, str], expression: Optional[str] = None)[source]

Bases: object

An object which defines how a target column is mapped to inserter definition.

Parameters
  • column_name – the column name.

  • expression – the SQL expression for computing the column If not set, the data for this column must be provided using add_row()/add_rows() calls during insertion

column_name

The name of the column.

expression

The SQL expression used to compute the column.

add_row(row: Iterable[object])[source]

Inserts a row of data into the table. None corresponds to the database NULL, see TypeTag for how Python types are mapped to Hyper data types.

Parameters

row – a row of data as a list of objects.

add_rows(rows: Iterable[Iterable[object]])[source]

Inserts rows of data into the table. Each row is represented by a sequence of objects. None corresponds to the database NULL, see TypeTag for how Python types are mapped to Hyper data types.

This is a convenience method equivalent to:

for row in rows:
    inserter.add_row(row)
Parameters

rows – a sequence of rows of data.

close()[source]

If the inserter is not closed yet, discard all data and close it.

execute()[source]

Flush remaining data and commit. If this method fails then the data is discarded and not inserted. The inserter is closed after this method returns, even in the case of a failure. If execute() is not called and the inserter is closed, then the inserted data is discarded.

is_open

Returns True if the inserter has not been closed yet.

class tableauhyperapi.Persistence[source]

Bases: enum.Enum

Persistence type of a table.

PERMANENT = 0

Table is permanent, stored in the database on disk.

TEMPORARY = 1

Table is temporary. It is only visible to the connection that created the table and will be deleted once this connection is closed.

class tableauhyperapi.Nullability[source]

Bases: enum.Enum

Constants which define whether a column may contain NULL values.

NOT_NULLABLE = 0

Column is not nullable, i.e., it may not contain NULL values.

NULLABLE = 1

Column is nullable, i.e., it may contain NULL values.

class tableauhyperapi.SqlType(tag: tableauhyperapi.TypeTag, modifier: int = 4294967295, oid: int = None)[source]

Bases: object

An object which represents a column type - type tag and optional type-specific modifiers.

Do not use the constructor directly, instead use one of the factory methods.

static big_int() → tableauhyperapi.SqlType[source]

Creates an instance of a BIG_INT type.

static bool() → tableauhyperapi.SqlType[source]

Creates an instance of a BOOL type.

static bytes() → tableauhyperapi.SqlType[source]

Creates an instance of a BYTES type.

static char(max_length: int) → tableauhyperapi.SqlType[source]

Creates an instance of a CHAR type.

static date() → tableauhyperapi.SqlType[source]

Creates an instance of a DATE type.

static double() → tableauhyperapi.SqlType[source]

Creates an instance of a DOUBLE type.

static geography() → tableauhyperapi.SqlType[source]

Creates an instance of a GEOGRAPHY type.

static int() → tableauhyperapi.SqlType[source]

Creates an instance of an INT type.

internal_oid

The underlying type OID. This property is internal and may change or go away in the future versions.

internal_type_modifier

The underlying type modifier. This property is internal and may change or go away in the future versions.

static interval() → tableauhyperapi.SqlType[source]

Creates an instance of an INTERVAL type.

static json() → tableauhyperapi.SqlType[source]

Creates an instance of a JSON type.

max_length

The max length of this type if it is CHAR or VARCHAR, otherwise None.

static numeric(precision: int, scale: int) → tableauhyperapi.SqlType[source]

Creates an instance of a NUMERIC type.

static oid() → tableauhyperapi.SqlType[source]

Creates an instance of an OID type.

precision

The precision, i.e., maximum number of digits, of a NUMERIC value.

scale

The scale, i.e., number of fractional digits, of a NUMERIC value.

static small_int() → tableauhyperapi.SqlType[source]

Creates an instance of a SMALL_INT type.

tag

The underlying type tag, one of the TypeTag constants.

static text() → tableauhyperapi.SqlType[source]

Creates an instance of a TEXT type.

static time() → tableauhyperapi.SqlType[source]

Creates an instance of a TIME type.

static timestamp() → tableauhyperapi.SqlType[source]

Creates an instance of a TIMESTAMP type.

static timestamp_tz() → tableauhyperapi.SqlType[source]

Creates an instance of a TIMESTAMP_TZ type.

static varchar(max_length: int) → tableauhyperapi.SqlType[source]

Creates an instance of a VARCHAR type.

class tableauhyperapi.TypeTag[source]

Bases: enum.Enum

Constants which represent Hyper data types. These are used as values of the SqlType.tag attribute.

BIG_INT = 2

Eight-byte integer values. Represented by Python’s int.

BOOL = 1

Boolean values. Represented by Python’s bool.

BYTES = 8

Byte array. These are returned as bytes objects from queries. When writing data, bytearray and bytes objects are accepted.

CHAR = 11

Space-padded unicode text. These are returned as str or UTF8-encoded bytes objects, depending on the str_as_bytes parameter of execute_query/execute_list_query/execute_scalar_query methods. When writing data, str, bytearray, and bytes objects are accepted. Bytes are assumed to be UTF8-encoded.

DATE = 13

Date values. These are returned as Date objects from queries. When writing data, datetime.date, datetime.datetime are also accepted; time part in datetime.datetime is ignored.

DOUBLE = 6

Double precision floating point values. Represented by Python’s float.

GEOGRAPHY = 18

Geography. These are returned as bytes objects from queries. When writing data, bytes and bytearray objects are accepted.

INT = 4

Four-byte integer values. Represented by Python’s int.

INTERVAL = 14

Time interval - union of logically independent months, days, and microseconds components. Represented by Interval objects.

JSON = 12

Unicode text. These are returned as str or UTF8-encoded bytes objects, depending on the str_as_bytes parameter of execute_query/execute_list_query/execute_scalar_query methods. When writing data, str, bytearray, and bytes objects are accepted. Bytes are assumed to be UTF8-encoded.

NUMERIC = 5

Exact decimal numbers with user-specified precision. Represented by decimal.Decimal.

OID = 7

OID values. Represented by Python’s int.

SMALL_INT = 3

Two-byte integer values. Represented by Python’s int.

TEXT = 9

Unicode text. These are returned as str or UTF8-encoded bytes objects, depending on the str_as_bytes parameter of execute_query/execute_list_query/execute_scalar_query methods. When writing data, str, bytearray, and bytes objects are accepted. Bytes are assumed to be UTF8-encoded.

TIME = 15

Time of the day, from 00:00:00 to 23:59:59:999999. These are returned as datetime.time objects from queries. When writing data, datetime.time and datetime.datetime objects are accepted; date part in datetime.datetime is ignored.

TIMESTAMP = 16

Timestamp - date and time of day. These are returned as Timestamp objects from queries. When writing data, datetime.datetime objects are also accepted.

TIMESTAMP_TZ = 17

UTC Timestamp - date and time of day. These are returned as Timestamp objects from queries. When writing data, datetime.datetime objects are also accepted.

UNSUPPORTED = 0

Unsupported type. Queries and tables may have columns of this type if the database was created by a newer version of the library. Values are represented by Python’s bytes.

VARCHAR = 10

Unicode text with maximum length. These are returned as str or UTF8-encoded bytes objects, depending on the str_as_bytes parameter of execute_query/execute_list_query/execute_scalar_query methods. When writing data, str, bytearray, and bytes objects are accepted. Bytes are assumed to be UTF8-encoded.

class tableauhyperapi.Name(name: Union[str, pathlib.PurePath, Name])[source]

Bases: object

An object which represents a SQL object name. It handles quoting and escaping strings to avoid SQL injection attacks.

Parameters

name – the raw, unquoted, unescaped name.

Example:

>>> print(Name('a table'))
"a table"
>>> print(f'DROP TABLE {Name("a table")}')
DROP TABLE "a table"
unescaped

The unescaped name that was used to create this name. Don’t use the result of this method in SQL, as it is prone to SQL injection. The method should be used where the original name is required (e.g., logging).

class tableauhyperapi.SchemaName(*components)[source]

Bases: object

An escaped and potentially qualified Schema Name.

Parameters

components – the unescaped components of the schema name.

Examples:

>>> print(SchemaName('schema'))
"schema"
>>> print(SchemaName('database', 'schema'))
"database"."schema"
>>> print('CREATE SCHEMA {}'.format(SchemaName('db', 'a schema')))
CREATE SCHEMA "db"."a schema"
database_name

The database name or None

is_fully_qualified

Is the schema name fully qualified, i.e., It contains a database name

name

The schema name, i.e., the last part of a fully qualified schema name.

class tableauhyperapi.TableName(*components)[source]

Bases: object

An escaped and potentially qualified TableName.

Parameters

components – the unescaped components of the table name.

Examples:

>>> print(TableName('table'))
"table"
>>> print(TableName('schema', 'table'))
"schema"."table"
>>> print(TableName('db', 'schema', 'table'))
"db"."schema"."table"
>>> print('CREATE TABLE {}'.format(TableName('db', 'schema', 'table')))
CREATE TABLE "db"."schema"."table"
>>> print('CREATE TABLE {}'.format(TableName('schema','table')))
CREATE TABLE "schema"."table"
database_name

The database name or None

is_fully_qualified

Is the table name fully qualified, i.e., it contains a schema name and a database name

name

The table name, i.e., the last part of a fully qualified table name.

schema_name

The schema name or None

class tableauhyperapi.DatabaseName(database_name: Union[str, pathlib.PurePath, Name, DatabaseName])[source]

Bases: object

An escaped Database Name

Parameters

database_name – the raw, unquoted, unescaped name.

Example:

>>> print(DatabaseName('database'))
"database"
>>> print(f'CREATE DATABASE {DatabaseName("a database")}')
CREATE DATABASE "a database"
name

The escaped and quoted database name

class tableauhyperapi.TableDefinition(table_name: Union[tableauhyperapi.Name, tableauhyperapi.TableName, str], columns: Optional[Iterable[tableauhyperapi.TableDefinition.Column]] = None, persistence: tableauhyperapi.Persistence = <Persistence.PERMANENT: 0>)[source]

Bases: object

A SQL table definition.

Parameters
  • table_name – the table name.

  • columns – an optional list of table columns.

  • persistence – an optional persistence mode for the table, PERMANENT by default.

Examples:

table_def = TableDefinition('products', [
    TableDefinition.Column('id', SqlType.int(), Nullability.NOT_NULLABLE),
    TableDefinition.Column('name', SqlType.text()),
    TableDefinition.Column('price', SqlType.double()),
])

table_def.add_column('category', SqlType.text())
class Column(name: Union[tableauhyperapi.Name, str], type: tableauhyperapi.SqlType, nullability: tableauhyperapi.Nullability = <Nullability.NULLABLE: 1>, collation: str = None)[source]

Bases: object

An object which represents a table column.

Parameters
  • name – the column name.

  • type – the column type.

  • nullability – the optional column nullability, NULLABLE by default.

  • collation – the text column collation, None by default. None means default binary collation.

collation

The collation of the column.

name

The name of the column.

nullability

The nullability of the column.

type

The type of the column.

add_column(*args, **kwargs) → tableauhyperapi.TableDefinition[source]

Adds a column. The parameters are either the Column object to add, or arguments for the Column constructor.

Returns

self.

Examples:

column = TableDefinition.Column("a", SqlType.int())
table_def.add_column(column)

table_def.add_column("b", SqlType.text(), collation='en_US_CI')
column_count

The number of columns in the table.

columns

The list of table columns. This list cannot be modified, use add_column() to add a new column.

get_column(position: int) → tableauhyperapi.TableDefinition.Column[source]

Gets the column at the given position.

Parameters

position – column position, must be in the range from 0 to column_count - 1.

Returns

the column.

get_column_by_name(name: Union[str, tableauhyperapi.Name]) → Optional[tableauhyperapi.TableDefinition.Column][source]

Gets the column with the given name if it exists.

Parameters

name – the column name.

Returns

the column, or None if it does not exist.

get_column_position_by_name(name: Union[str, tableauhyperapi.Name]) → Optional[int][source]

Gets the position of the column with the given name.

Parameters

name – the column name.

Returns

the column position, or None if it does not exist.

persistence

Returns the table’s persistence mode.

table_name

Returns the table name.

tableauhyperapi.escape_name(identifier: Union[str, pathlib.PurePath]) → str[source]

Quotes and escapes an identifier for use in SQL queries..

Parameters

identifier – the identifier to quote.

Returns

a properly quoted and escaped string representing the name.

Example:

>>> print(escape_name('a table'))
"a table"
>>> print(f'DROP TABLE {escape_name("a table")}')
DROP TABLE "a table"
tableauhyperapi.escape_string_literal(literal: str) → str[source]

Quotes and escapes a string literal for use in SQL queries.

Parameters

literal – the string to escape.

Returns

the quoted string, including the quotes.

Example:

>>> print(f'SELECT * FROM foo WHERE a = {escape_string_literal("abc")}')
SELECT * FROM foo WHERE a = 'abc'
class tableauhyperapi.Date(year, month, day)[source]

Bases: object

A Hyper DATE value - year, month, and day.

This class is similar to datetime.date. The difference is that it supports a greater range of dates: while Python years range from 1 to 9999, Hyper supports years from -4712 (4713 BC) to 294276.

Parameters
  • year – the year.

  • month – the month, from 1 to 12.

  • day – the day, from 1 to the number of days in the month.

>>> print(Date(2019, 6, 13))
2019-06-13
MAXYEAR = 294276

The latest representable year.

MINYEAR = -4712

The earliest representable year.

day

The day.

static from_date(date: datetime.date) → tableauhyperapi.Date[source]

Converts Python datetime.date to Date.

month

The month.

to_date() → datetime.date[source]

Converts to Python datetime.date. Raises an exception if the date is not representable by the Python class.

static today() → tableauhyperapi.Date[source]

Returns the current local date.

year

The year.

class tableauhyperapi.Timestamp(*args, tzinfo=None)[source]

Bases: object

A Hyper timestamp - date and time of day.

This class is similar to datetime.datetime. The difference is that it supports a greater range of dates: while Python years range from 1 to 9999, Hyper supports years from -4712 (4713 BC) to 294276.

Parameters
  • year – Year.

  • month – Month, from 1 to 12.

  • day – Day, from 1 to the number of days in the month.

  • hour – Optional hour value, from 0 to 23.

  • minute – Optional minute value, from 0 to 59.

  • second – Optional second value, from 0 to 59.

  • microsecond – Optional microsecond value, from 0 to 999_999.

  • tzinfo – Optional tzinfo value, may be None or an instance of a tzinfo subclass.

>>> print(Timestamp(2019, 6, 13))
2019-06-13 00:00:00
>>> print(Timestamp(2019, 6, 13, 13, 23, 45))
2019-06-13 13:23:45
>>> print(Timestamp(2019, 6, 13, 13, 23, 45, 789876))
2019-06-13 13:23:45.789876
MAXYEAR = 294276

The latest representable year.

MINYEAR = -4712

The earliest representable year.

astimezone(tz=None)[source]

Return a Timestamp object with new tzinfo attribute tz, adjusting the date and time data so the result is the same UTC time as self, but in tz’s local time.

If provided, tz must be an instance of a tzinfo subclass, and its utcoffset() and dst() methods must not return None. If self is naive, it is presumed to represent time in the system timezone.

If called without arguments (or with tz=None) the system local timezone is assumed for the target timezone. The .tzinfo attribute of the converted timestamp instance will be set to an instance of timezone with the zone name and offset obtained from the OS.

date() → tableauhyperapi.Timestamp[source]

Gets the date part of this value.

day

Gets the day part of this value, as a number between 1 and the number of days in the month.

static from_date(value: [<class 'datetime.date'>, 'date.Date']) → tableauhyperapi.Timestamp[source]

Converts a Python datetime.date or Date value to a Timestamp.

static from_datetime(value: datetime.datetime) → tableauhyperapi.Timestamp[source]

Converts a Python datetime.datetime value to a Timestamp.

hour

Gets the hour part of this value, as a number between 0 and 23.

microsecond

Gets the second part of this value, as an integer between 0 and 999999.

minute

Gets the minute part of this value, as a number between 0 and 59.

month

Gets the month part of this value, as a number between 1 and 12.

static now(tz=None) → tableauhyperapi.Timestamp[source]

Returns the current local date and time. If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone.

second

Gets the second part of this value, as an integer between 0 and 59.

to_date() → tableauhyperapi.Date[source]

Gets the date part of this value as a Date.

to_datetime() → datetime.datetime[source]

Converts this value to Python datetime.datetime.

static today() → tableauhyperapi.Timestamp[source]

Returns the current local date.

tzinfo

Gets the tzinfo of this value, may be None or an instance of a tzinfo subclass.

utcoffset() → datetime.timedelta[source]

If tzinfo is None, returns None. Otherwise, returns the timedelta returned by self.tzinfo.utcoffset(datetime). datetime is obtained by converting the timestamp to a datetime restricting the year to the range datetime.MINYEAR..datetime.MAXYEAR. This method raises an exception if self.tzinfo.utcoffset(datetime) doesn’t return None or a timedelta object representing a whole number of minutes with magnitude less than one day.

year

Gets the year part of this value.

class tableauhyperapi.Interval(months: int, days: int, microseconds: int)[source]

Bases: object

A Hyper INTERVAL. It is a union of logically independent months, days, and microseconds components, which expresses time intervals like “1 year” (which may mean 365 or 366 days depending on to which date it is added), “2 months” (which has variable number of days depending on the month), “3 days” (which may mean different number of hours if daylight savings changed), “4 hours”, “5 seconds”.

Parameters
  • months – the number of months.

  • days – the number of days.

  • microseconds – the number of microseconds.

Examples:

>>> print(Interval(1, 0, 0)) # 1 month
P1M
>>> print(Interval(0, 1, 0)) # 1 day
P1D
>>> print(Interval(0, 0, 1_000_000)) # 1 second
PT1.0S

Interval values can be added and subtracted, which performs component-wise addition or subtraction.

Comparison for Interval values is lexicographic on their components, for instance 1 day does not equal 24 hours. Similarly 1 year compares greater than 400 days.

days

The days component.

microseconds

The microseconds component.

months

The months component.

exception tableauhyperapi.UnclosedObjectWarning[source]

Bases: Warning

Warning issued when a HyperProcess, Connection, Result or Inserter object has not been properly closed (e.g., by a with statement or explicit shutdown() or close() method.)

class tableauhyperapi.HyperServiceVersion(major, minor)[source]

Bases: object

A Hyper Service version number of the form ‘major.minor’. :param major: The major part of the version number. :param minor: The minor part of the version number.

major

The major part of the version number.

minor

The minor part of the version number.

tableauhyperapi.__version__ = '0.0.13821'

PEP-396-compliant version number of the library.

tableauhyperapi.VERSION = (0, 0, 13821)

Version number of the library as a tuple (major, minor, micro).