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
An exception raised by the Hyper API. |
|
Starts a local Hyper server instance managed by the library. |
|
Connects to a Hyper server. |
|
A network endpoint to which a connection can be established. |
|
The class which is responsible for querying and manipulating metadata. |
|
An object which is used to insert data into a table. |
|
A SQL table definition. |
|
Persistence type of a table. |
|
An object which is used to read query results. |
|
The schema of a query result. |
|
Constants which represent Hyper data types. |
|
An object which represents a column type - type tag and optional type-specific modifiers. |
|
An object which represents a SQL object name. |
|
An escaped Database Name |
|
An escaped and potentially qualified Schema Name. |
|
An escaped and potentially qualified TableName. |
|
A Hyper DATE value - year, month, and day. |
|
A Hyper timestamp - date and time of day. |
|
A Hyper INTERVAL. |
|
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_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.
- 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:
endpoint –
Endpoint
which specifies the Hyper instance to connect to.database – Optional path to the database file.
create_mode – If database path is specified, defines what happens if the database already exists. By default it is
CreateMode.NONE
.parameters – Optional dictionary of connection parameters to pass to Hyper. The available parameters are documented in the Tableau Hyper documentation, chapter “Connection Settings”.
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.
- 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-encodedbytearray
objects. By default string values are returned asstr
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-encodedbytearray
objects. By default string values are returned asstr
objects.
- Returns:
A
Result
instance. Use this method in awith
statement to automatically close the result when done reading from it, or call itsclose()
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-encodedbytearray
objects. By default string values are returned asstr
objects.
- Returns:
the value from the result. A NULL database value is returned as
None
. SeeTypeTag
documentation for how database values are represented by Python objects.
- property is_open: bool
Returns
True
if the connection has not been closed yet.
- 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"
- 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) to294276
.- 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.
- 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.
- 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:
telemetry –
Telemetry
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 theclose()
orshutdown()
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. Useshutdown()
instead ofclose()
to get the shutdown errors as aHyperException
.
- 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 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, seeTypeTag
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, seeTypeTag
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.
- 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
. SeeTypeTag
documentation for how Hyper data types map to Python types.The
Result
constructor may not be used directly, useConnection.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()
returnedTrue
.- Parameters:
column_index – the column index.
- Returns:
the value as the corresponding python object if it is non-NULL, or
None
otherwise. SeeTypeTag
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()
returnedTrue
.- Returns:
the row values as a list of objects. NULL is represented by
None
, seeTypeTag
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.
- property column_count: int
The column count.
- 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.
- 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
- 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.
- 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.
- property max_length: int | None
The max length of this type if it is
CHAR
orVARCHAR
, otherwiseNone
.
- static timestamp_tz() SqlType [source]
Creates an instance of a
TIMESTAMP_TZ
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 nullability: Nullability
The nullability 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 theColumn
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.
- 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 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) to294276
.- 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.
- 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
orDate
value to aTimestamp
.
- static from_datetime(value: datetime) Timestamp [source]
Converts a Python
datetime.datetime
value to aTimestamp
.
- 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.
- 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
andbytes
objects are accepted.
- CHAR = 11
Space-padded unicode text. These are returned as
str
or UTF8-encodedbytes
objects, depending on thestr_as_bytes
parameter ofexecute_query
/execute_list_query
/execute_scalar_query
methods. When writing data,str
,bytearray
, andbytes
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 indatetime.datetime
is ignored.
- DOUBLE = 6
Double precision floating point values. Represented by Python’s
float
.
- FLOAT = 19
Single precision floating point values. Represented by Python’s
float
.
- GEOGRAPHY = 18
Geography. These are returned as
bytes
objects from queries. When writing data,bytes
andbytearray
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-encodedbytes
objects, depending on thestr_as_bytes
parameter ofexecute_query
/execute_list_query
/execute_scalar_query
methods. When writing data,str
,bytearray
, andbytes
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-encodedbytes
objects, depending on thestr_as_bytes
parameter ofexecute_query
/execute_list_query
/execute_scalar_query
methods. When writing data,str
,bytearray
, andbytes
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
anddatetime.datetime
objects are accepted; date part indatetime.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-encodedbytes
objects, depending on thestr_as_bytes
parameter ofexecute_query
/execute_list_query
/execute_scalar_query
methods. When writing data,str
,bytearray
, andbytes
objects are accepted. Bytes are assumed to be UTF8-encoded.
- exception tableauhyperapi.UnclosedObjectWarning[source]
Bases:
Warning
Warning issued when a
HyperProcess
,Connection
,Result
orInserter
object has not been properly closed (e.g., by awith
statement or explicitshutdown()
orclose()
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.20746'
PEP-396-compliant version number of the library.
- tableauhyperapi.VERSION = (0, 0, 20746)
Version number of the library as a tuple (major, minor, micro).