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'.

class tableauhyperapi.Catalog(connection: 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: str | PurePath, alias: str | Name | DatabaseName | None = None)[source]

Attaches a database to the underlying connection.

property connection: Connection

Gets the underlying connection.

create_database(database_path: str | 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: str | 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: str | Name | 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: str | Name | 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: 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: 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: str | Name | DatabaseName)[source]

Detaches a database from the underlying connection.

drop_database(database_path: str | PurePath)[source]

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

drop_database_if_exists(database_path: str | PurePath)[source]

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

get_schema_names(database: DatabaseName | Name | str = None) List[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: TableName | Name | str) TableDefinition[source]

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

get_table_names(schema: SchemaName | Name | str) List[TableName][source]

Gets the names of all tables in the specified schema.

has_table(name: TableName | Name | str) bool[source]

Does a table with this name exist?

class tableauhyperapi.Connection(endpoint: Endpoint, database: str | PurePath | None = None, create_mode: CreateMode | None = CreateMode.NONE, parameters: Mapping[str, str] | None = 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.

property catalog: 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) int | None[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[bool | bytearray | bytes | time | Date | Decimal | float | int | Interval | str | 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) 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) bool | bytearray | bytes | time | Date | Decimal | float | int | Interval | str | 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() 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.

property is_open: bool

Returns True if the connection has not been closed yet.

property is_ready: bool

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: Endpoint) List[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.CreateMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: 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.DatabaseName(database_name: str | 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"
property name: Name

The escaped and quoted database name

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: date) Date[source]

Converts Python datetime.date to Date.

month

The month.

to_date() date[source]

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

static today() Date[source]

Returns the current local date.

year

The year.

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.

property connection_descriptor: str

The string representation of the endpoint.

property user_agent: str

The user agent.

exception tableauhyperapi.HyperException(context_id: ContextId, main_message: str | None = None, hint: str | None = None, message: str | None = None, hint_message: str | None = 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: ContextId

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

hint: str | None

A possible hint on how to fix the error.

property hint_message: str | None

A possible hint on how to fix the error.

Warning

Deprecated: Use hint

main_message: str | None

The main message of this exception.

property message: str | None

The main message of this exception.

Warning

Deprecated: Use main_message

class tableauhyperapi.HyperProcess(telemetry: Telemetry, user_agent: str = '', hyper_path: str | 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.

property endpoint: Endpoint

Endpoint of this process to connect to.

property is_open: bool

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.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.

property major: int

The major part of the version number.

property minor: int

The minor part of the version number.

class tableauhyperapi.Inserter(connection: Connection, arg: str | Name | TableName | TableDefinition, columns: Iterable[str | ColumnMapping] = None, *, inserter_definition: Iterable[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: Name | str, expression: str | None = 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

property column_name: Name

The name of the column.

property expression: str | None

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.

property is_open: bool

Returns True if the inserter has not been closed yet.

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.

class tableauhyperapi.Name(name: str | 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"
property unescaped: str

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.Nullability(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: 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.Persistence(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: 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.Result(text_as_bytes: bool, connection: 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.

property affected_row_count: int | None

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.

property connection: 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[bool | bytearray | bytes | time | Date | Decimal | float | int | Interval | str | 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.

property is_open: bool

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.

property schema: ResultSchema

Gets the result schema.

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

Bases: object

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

class Column(name: Name | str, type: SqlType)[source]

Bases: object

A result column.

property name: Name

The name of the column.

property type: SqlType

The type of the column.

property column_count: int

The column count.

property columns: Tuple[Column, ...]

The list of the columns.

get_column(position: int) 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: Name | str) Column | None[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: str | Name) int | None[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.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"
property database_name: DatabaseName | None

The database name or None

property is_fully_qualified: bool

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

property name: Name

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

class tableauhyperapi.SqlType(tag: 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() SqlType[source]

Creates an instance of a BIG_INT type.

static bool() SqlType[source]

Creates an instance of a BOOL type.

static bytes() SqlType[source]

Creates an instance of a BYTES type.

static char(max_length: int) SqlType[source]

Creates an instance of a CHAR type.

static date() SqlType[source]

Creates an instance of a DATE type.

static double() SqlType[source]

Creates an instance of a DOUBLE type.

static geography() SqlType[source]

Creates an instance of a GEOGRAPHY type.

static int() SqlType[source]

Creates an instance of an INT type.

property internal_oid: int

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

property internal_type_modifier: int

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

static interval() SqlType[source]

Creates an instance of an INTERVAL type.

static json() SqlType[source]

Creates an instance of a JSON type.

property max_length: int | None

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

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

Creates an instance of a NUMERIC type.

static oid() SqlType[source]

Creates an instance of an OID type.

property precision: int | None

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

property scale: int | None

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

static small_int() SqlType[source]

Creates an instance of a SMALL_INT type.

property tag: TypeTag

The underlying type tag, one of the TypeTag constants.

static text() SqlType[source]

Creates an instance of a TEXT type.

static time() SqlType[source]

Creates an instance of a TIME type.

static timestamp() SqlType[source]

Creates an instance of a TIMESTAMP type.

static timestamp_tz() SqlType[source]

Creates an instance of a TIMESTAMP_TZ type.

static varchar(max_length: int) SqlType[source]

Creates an instance of a VARCHAR type.

class tableauhyperapi.TableDefinition(table_name: Name | TableName | str, columns: Iterable[Column] | None = None, persistence: Persistence = Persistence.PERMANENT)[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: Name | str, type: SqlType, nullability: Nullability = Nullability.NULLABLE, 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.

property collation: str | None

The collation of the column.

property name: Name

The name of the column.

property nullability: Nullability

The nullability of the column.

property type: SqlType

The type of the column.

add_column(column: Column) TableDefinition[source]
add_column(name: str, type: SqlType, nullability: Nullability = Nullability.NULLABLE, collation: str = None) TableDefinition

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')
property column_count: int

The number of columns in the table.

property columns: Sequence[Column]

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

get_column(position: int) 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: str | Name) Column | None[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: str | Name) int | None[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.

property persistence: Persistence

Returns the table’s persistence mode.

property table_name: TableName

Returns the table 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"
property database_name: DatabaseName | None

The database name or None

property is_fully_qualified: bool

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

property name: Name

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

property schema_name: SchemaName | None

The schema name or None

class tableauhyperapi.Telemetry(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: 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.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() Timestamp[source]

Gets the date part of this value.

property day: int

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']) Timestamp[source]

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

static from_datetime(value: datetime) Timestamp[source]

Converts a Python datetime.datetime value to a Timestamp.

property hour: int

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

property microsecond: int

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

property minute: int

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

property month: int

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

static now(tz=None) 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.

property second: int

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

to_date() Date[source]

Gets the date part of this value as a Date.

to_datetime() datetime[source]

Converts this value to Python datetime.datetime.

static today() Timestamp[source]

Returns the current local date.

property tzinfo: tzinfo

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

utcoffset() 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.

property year: int

Gets the year part of this value.

class tableauhyperapi.TypeTag(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: 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.

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.)

tableauhyperapi.escape_name(identifier: str | 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'
tableauhyperapi.__version__ = '0.0.18825'

PEP-396-compliant version number of the library.

tableauhyperapi.VERSION = (0, 0, 18825)

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