### Setup Virtual Environment and Dependencies Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/tde-to-hyper/README.md Commands to initialize a Python virtual environment and install the required Hyper API dependencies. ```bash $ python3 -m venv .venv/ $ .venv/bin/python3 -m pip install -r requirements.txt ``` -------------------------------- ### Install AWS SDK and CLI Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Install Boto3 and configure the AWS CLI for authentication. ```console pip install boto3 ``` ```console aws configure ``` -------------------------------- ### Install BigQuery Python Client Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Install the standard BigQuery client library for Python. ```console pip install google-cloud-bigquery ``` -------------------------------- ### Install Tableau Server Client Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Installs the required Tableau Server client libraries. ```console pip install tableauserverclient ``` -------------------------------- ### Install hyper_kernel for Command-Line Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/hyper-jupyter-kernel/README.md Installs jupyter-console and the hyper_kernel. Launch the console using the provided command. ```bash python3 -m pip install jupyter-console tableauhyperapi git+https://github.com/tableau/hyper-api-samples#subdirectory=Community-Supported/hyper-jupyter-kernel python3 -m hyper_kernel.install ``` ```bash jupyter console --kernel=hyper ``` -------------------------------- ### Setup Virtual Environment Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Creates and activates a Python virtual environment. ```console python3 -m venv env source env/bin/activate ``` -------------------------------- ### Install hyper_kernel for JupyterLab Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/hyper-jupyter-kernel/README.md Installs JupyterLab and the hyper_kernel. Launch JupyterLab using the provided command. ```bash python3 -m pip install jupyterlab tableauhyperapi git+https://github.com/tableau/hyper-api-samples#subdirectory=Community-Supported/hyper-jupyter-kernel python3 -m hyper_kernel.install ``` ```bash python3 -m jupyter lab --core-mode ``` -------------------------------- ### Install Hyper API Client Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Installs the required Tableau Hyper API client libraries. ```console pip install --upgrade pip pip install tableauhyperapi ``` -------------------------------- ### Clone and Run the Advanced Sample Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/git-to-hyper/README.md Commands to clone the repository, install dependencies, and execute the advanced sample script. ```bash $ git clone https://github.com/tableau/hyper-api-samples.git $ cd hyper-api-samples $ pip3 install -r Community-Supported/git-to-hyper/requirements.txt $ python Community-Supported/git-to-hyper/advanced-git-to-hyper.py --path_to_repo ~/sample/repository ``` -------------------------------- ### Install Dependencies Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Installs third-party Python library dependencies from the requirements file. ```console cd hyper-api-samples/Community-Supported/clouddb-extractor pip install -r requirements.txt ``` -------------------------------- ### Install Redshift Connector Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Install the Python driver for Amazon Redshift. ```console pip install redshift_connector ``` -------------------------------- ### Install Hyper API dependencies Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/pandas-to-hyper/README.md Install the required Python packages listed in the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Example script output Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/pandas-to-hyper/README.md Expected console output after successfully running the data loading script. ```text EXAMPLE - Load data from pandas DataFrame into table in new Hyper file The number of rows in table Customer is 3. The connection to the Hyper file has been closed. The Hyper process has been shut down. ``` -------------------------------- ### Run the basic git-to-hyper sample Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/git-to-hyper/README.md Commands to clone the repository, install dependencies, and execute the extraction script on a target repository. ```bash $ git clone https://github.com/tableau/hyper-api-samples.git $ cd hyper-api-samples $ pip3 install -r Community-Supported/git-to-hyper/requirements.txt $ python Community-Supported/git-to-hyper/basic-git-to-hyper.py --path_to_repo ~/sample/repository ``` -------------------------------- ### Install MySQL Connector Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Install the MySQL connector for Python using pip. This is required for connecting to MySQL databases. ```bash pip install mysql-connector-python ``` -------------------------------- ### Build and Test Insert Data into Multiple Tables Example Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Builds the `insert_data_into_multiple_tables` executable and sets up a test for it. This example shows how to insert data into several tables within a Hyper file. ```cmake add_executable(insert_data_into_multiple_tables insert_data_into_multiple_tables.cpp) target_link_libraries(insert_data_into_multiple_tables PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME insert_data_into_multiple_tables COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Create Multi-Table Hyper Files (Python) Source: https://context7.com/tableau/hyper-api-samples/llms.txt Demonstrates the setup for creating Hyper files with multiple related tables, including primary and foreign key constraints. This is useful for data model inference on Tableau Server. ```python from datetime import datetime from pathlib import Path from tableauhyperapi import ( HyperProcess, Telemetry, Connection, CreateMode, NOT_NULLABLE, NULLABLE, SqlType, TableDefinition, Inserter, HyperException ) ``` -------------------------------- ### Start HyperProcess in Python Source: https://context7.com/tableau/hyper-api-samples/llms.txt Initializes the Hyper database engine as a context manager to ensure automatic shutdown. ```python from tableauhyperapi import HyperProcess, Telemetry # Optional process parameters for logging configuration process_parameters = { "log_file_max_count": "2", "log_file_size_limit": "100M" } # Start Hyper process with telemetry enabled with HyperProcess( telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU, parameters=process_parameters ) as hyper: # Hyper engine is running, perform database operations here print(f"Hyper process started at endpoint: {hyper.endpoint}") # Process automatically shuts down when exiting context print("Hyper process has been shut down") ``` -------------------------------- ### Build and Test Insert Data with Expressions Example Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Builds the `insert_data_with_expressions` executable and includes a test for it. This example demonstrates inserting data into a Hyper file using expressions. ```cmake add_executable(insert_data_with_expressions insert_data_with_expressions.cpp) target_link_libraries(insert_data_with_expressions PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME insert_data_with_expressions COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Install PostgreSQL Psycopg2 Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Install the Psycopg2 binary package for PostgreSQL using pip. This library is needed for PostgreSQL connections. ```bash pip install psycopg2-binary ``` -------------------------------- ### Install BigQuery Storage and DBAPI Libraries Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Additional libraries required when configuring bigquery_extractor to use DBAPIv2 for performance advantages. ```console pip install google-cloud-bigquery-storage pip install pyarrow ``` -------------------------------- ### Configure Redshift Connection Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Example configuration for Redshift connection parameters in config.yml. ```yaml redshift: #Redshift configuration defualts connection: host : 'redshift-cluster-1.xxxxxxxxx.eu-west-1.redshift.amazonaws.com' database : 'dev' user : 'db_username' password : 'db_password' ``` -------------------------------- ### Execute vertex order adjustment Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/adjust-vertex-order/README.md Example command to run the vertex order adjustment on a .hyper file. ```bash $ python3 adjust_vertex_order.py run -i ./europe_interior_right.hyper -o ./europe_interior_left.hyper -m auto Adjusting vertex order of polygons assuming data source with flat - earth topology in spatial columns Copying table "input"."Extract"."Extract" with 1 spatial columns: [Name('Location')]... 1 rows copied ``` -------------------------------- ### Copy Data Files for Hyper API Examples Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Copies necessary data files, including sample extracts and normalized Superstore data, to the build directory. This ensures that the examples have the required datasets to run. ```cmake file(COPY "${CMAKE_SOURCE_DIR}/data/sample_extracts/" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/data") file(COPY "${CMAKE_SOURCE_DIR}/data/superstore_normalized/" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/data") ``` -------------------------------- ### Build and Test Insert Data into Single Table Example Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Builds the `insert_data_into_single_table` executable and adds a corresponding test. This example focuses on inserting data into a single table in a Hyper file. ```cmake add_executable(insert_data_into_single_table insert_data_into_single_table.cpp) target_link_libraries(insert_data_into_single_table PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME insert_data_into_single_table COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Build and Test Delete Data Example Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Builds the `delete_data_in_existing_hyper_file` executable and adds a test for it. This example demonstrates how to remove data from an existing Hyper file. ```cmake add_executable(delete_data_in_existing_hyper_file delete_data_in_existing_hyper_file.cpp) target_link_libraries(delete_data_in_existing_hyper_file PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME delete_data_in_existing_hyper_file COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Build and Test Create Hyper File Example Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Builds the `create_hyper_file_from_csv` executable and adds a test to run it. The test ensures the Hyper file is created correctly from a CSV source. ```cmake add_executable(create_hyper_file_from_csv create_hyper_file_from_csv.cpp) target_link_libraries(create_hyper_file_from_csv PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME create_hyper_file_from_csv COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### MySQL Connection Configuration Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Configure connection parameters for a MySQL database. Ensure these details match your MySQL server setup. ```yaml mysql: connection: host : "mysql.test" database : "dev" port : 3306 username : "test" password : "password" raise_on_warnings : True ``` -------------------------------- ### Copy Hyper API Dynamic Libraries for Windows Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt On Windows, this command copies the Hyper API dynamic libraries to the current binary directory. This is necessary for the examples to locate and load the libraries during execution. ```cmake if (WIN32) # On Windows, the Hyper API is copied into the binary directory so the examples can pick it up during execution. # On Posix systems, the Hyper API path is already compiled into the RPATH of the examples. file(COPY "${tableauhyperapi-c_DYLIB_DIR}/" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}") endif () ``` -------------------------------- ### View Advanced Sample Help Options Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/git-to-hyper/README.md Command to display the available command-line arguments and options for the advanced sample script. ```bash $ python Community-Supported/git-to-hyper/advanced-git-to-hyper.py --help usage: advanced-git-to-hyper.py [-h] [--branch BRANCH] [--ram_disk_dir RAM_DISK_DIR] [--number_of_workers NUMBER_OF_WORKERS] [--file_size_limit FILE_SIZE_LIMIT] [--blame_only_for_head] [--verbose] path_to_repo positional arguments: path_to_repo Path to the repository, e.g. ~/src/repo options: -h, --help show this help message and exit --branch BRANCH Branch to follow in the repository. Default: main --ram_disk_dir RAM_DISK_DIR Path to ram disk on the host machine. Used to improve the execution time by speeding up I/O heavy git operations. using "/dev/shm" should work for most Linux OS, if you are using a different OS you might need to create the ram disk manually first. It needs to have at least the size of the repository. --number_of_workers NUMBER_OF_WORKERS How many parallel processes shall be used for the data extraction --file_size_limit FILE_SIZE_LIMIT Files bigger than this limit are not analyzed. The unit is byte. Can be turned off by setting it to None. Default: 10 MB --blame_only_for_head Run git blame only for the HEAD commit to speed up the data collection --verbose Increase verbosity, e.g. print filenames of git blame targets ``` -------------------------------- ### Initialize Google Cloud SDK Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Commands to initialize the gcloud environment and verify account and configuration settings. ```console (env) myuser@emea-client-linux:~$ gcloud init Welcome! This command will take you through the configuration of gcloud. .... Your Google Cloud SDK is configured and ready to use! * Commands that require authentication will use XXX061130084-compute@developer.gserviceaccount.com by default * Commands will reference project `pre-sales-demo` by default * Compute Engine commands will use region `europe-west4` by default * Compute Engine commands will use zone `europe-west4-a` by default Run `gcloud help config` to learn how to change individual settings This gcloud configuration is called [default]. You can create additional configurations if you work with multiple accounts and/or projects. Run `gcloud topic configurations` to learn more. Some things to try next: * Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command. * Run `gcloud topic --help` to learn about advanced features of the SDK like arg files and output formatting (env) myuser@emea-client-linux:~$ gcloud auth list Credentialed Accounts ACTIVE ACCOUNT * XXX061130084-compute@developer.gserviceaccount.com To set the active account, run: $ gcloud config set account `ACCOUNT` (env) myuser@emea-client-linux:~$ gcloud config configurations list NAME IS_ACTIVE ACCOUNT PROJECT COMPUTE_DEFAULT_ZONE COMPUTE_DEFAULT_REGION default True XXX061130084-compute@developer.gserviceaccount.com pre-sales-demo europe-west4-a europe-west4 ``` -------------------------------- ### View git-to-hyper help options Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/git-to-hyper/README.md Displays the command-line arguments and options available for the basic-git-to-hyper.py script. ```bash $ python Community-Supported/git-to-hyper/basic-git-to-hyper.py --help usage: basic-git-to-hyper.py [-h] [--branch BRANCH] path_to_repo positional arguments: path_to_repo Path to the repository, e.g. ~/src/repo options: -h, --help show this help message and exit --branch BRANCH Branch to follow in the repository. Default: main ``` -------------------------------- ### Display run command syntax Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/adjust-vertex-order/README.md Shows the arguments required to execute the vertex order adjustment. ```text usage: adjust_vertex_order.py run [-h] -i -o -m {AdjustVertexOrderMode.AUTO,AdjustVertexOrderMode.INVERT} optional arguments: -h, --help show this help message and exit -i , --input_file Input .hyper file -o , --output_file Output .hyper file -m {AdjustVertexOrderMode.AUTO,AdjustVertexOrderMode.INVERT}, --mode {AdjustVertexOrderMode.AUTO,AdjustVertexOrderMode.INVERT} Vertex order adjustment mode: (auto | invert). Auto: assuming data comes from a source with a flat - earth topology, it automatically adjusts the vertex order according to the interior - left definition of polygons. Invert: inverts the vertex order for all polygons. ``` -------------------------------- ### Configure Read and Print Data Sample Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Defines the executable and test environment for the data reading sample. ```cmake add_executable(read_and_print_data_from_existing_hyper_file read_and_print_data_from_existing_hyper_file.cpp) target_link_libraries(read_and_print_data_from_existing_hyper_file PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME read_and_print_data_from_existing_hyper_file COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Load Sample Data via CLI Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Loads a sample of data from a source table into a specified Tableau datasource. ```console python3 extractor_cli.py load_sample --source_table_id test_table --tableau_project test_project --tableau_datasource sample_extract ``` -------------------------------- ### Create a Hyper Database Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/hyper-jupyter-kernel/README.md SQL commands to create a new Hyper database file. ```sql CREATE DATABASE "my_data.hyper"; ``` -------------------------------- ### Run a Simple SQL Query Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/hyper-jupyter-kernel/README.md Execute a basic SQL query to test the hyper_kernel. ```sql SELECT 12/2 AS result ``` -------------------------------- ### Create Tables and Insert Data Source: https://context7.com/tableau/hyper-api-samples/llms.txt Initialize a Hyper process, create tables, define constraints, and insert rows using the Inserter class. ```python path_to_database = Path("superstore.hyper") try: with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper: with Connection( endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE ) as connection: # Create all tables connection.catalog.create_table(table_definition=orders_table) connection.catalog.create_table(table_definition=customer_table) connection.catalog.create_table(table_definition=products_table) connection.catalog.create_table(table_definition=line_items_table) # Add constraints for Tableau Server data model inference (2021.4+) connection.execute_command( f'ALTER TABLE {customer_table.table_name} ADD ASSUMED PRIMARY KEY ("Customer ID")' ) connection.execute_command( f'''ALTER TABLE {orders_table.table_name} ADD ASSUMED FOREIGN KEY ("Customer ID") REFERENCES {customer_table.table_name} ("Customer ID")''' ) # Insert data into each table with Inserter(connection, orders_table) as inserter: inserter.add_rows([ [399, "DK-13375", datetime(2012, 9, 7), "CA-2011-100006", datetime(2012, 9, 13), "Standard Class"], [530, "EB-13705", datetime(2012, 7, 8), "CA-2011-100090", datetime(2012, 7, 12), "Standard Class"] ]) inserter.execute() with Inserter(connection, customer_table) as inserter: inserter.add_rows([ ["DK-13375", "Dennis Kane", 518, "Consumer"], ["EB-13705", "Ed Braxton", 815, "Corporate"] ]) inserter.execute() with Inserter(connection, products_table) as inserter: inserter.add_row(["Technology", "TEC-PH-10002075", "AT&T Phone", "Phones"]) inserter.execute() with Inserter(connection, line_items_table) as inserter: inserter.add_rows([ [2718, "CA-2011-100006", "TEC-PH-10002075", 377.97, 3, 0.0, 109.61], [2719, "CA-2011-100090", "TEC-PH-10002075", 377.97, 3, None, 109.61] ]) inserter.execute() # Verify row counts for table in [orders_table, customer_table, products_table, line_items_table]: ``` -------------------------------- ### Create and Insert Data into Hyper File Source: https://context7.com/tableau/hyper-api-samples/llms.txt Demonstrates creating a new Hyper file, defining a table schema, and inserting data from a Pandas DataFrame. Ensure necessary imports and DataFrame are prepared before execution. ```python import pandas as pd from pathlib import Path from tableauhyperapi import (HyperProcess, Telemetry, Connection, CreateMode, TableDefinition, SqlType, NOT_NULLABLE, Inserter, HyperException) # Create sample DataFrame data = { "Customer ID": ["DK-13375", "EB-13705", "JH-13600"], "Customer Name": ["John Doe", "Jane Smith", "Alice Johnson"], "Loyalty Reward Points": [100, 200, 300], "Segment": ["Consumer", "Corporate", "Home Office"], } df = pd.DataFrame(data) path_to_database = Path("customer.hyper") process_parameters = { "log_file_max_count": "2", "log_file_size_limit": "100M", } try: with HyperProcess( telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU, parameters=process_parameters ) as hyper: with Connection( endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE, parameters={"lc_time": "en_US"} ) as connection: # Define table matching DataFrame structure customer_table = TableDefinition( table_name="Customer", columns=[ TableDefinition.Column("Customer ID", SqlType.text(), NOT_NULLABLE), TableDefinition.Column("Customer Name", SqlType.text(), NOT_NULLABLE), TableDefinition.Column("Loyalty Reward Points", SqlType.big_int(), NOT_NULLABLE), TableDefinition.Column("Segment", SqlType.text(), NOT_NULLABLE), ], ) connection.catalog.create_table(table_definition=customer_table) # Insert DataFrame rows with Inserter(connection, customer_table) as inserter: for row in df.itertuples(index=False, name=None): inserter.add_row(row) inserter.execute() row_count = connection.execute_scalar_query( f"SELECT COUNT(*) FROM {customer_table.table_name}" ) print(f"Inserted {row_count} rows from DataFrame") except HyperException as ex: print(f"Error: {ex}") ``` -------------------------------- ### Configure CMake Project for Hyper API Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Sets up the CMake build system to find and use the Tableau Hyper API for C++. It allows overriding the installation path and the Hyper executable path. ```cmake cmake_minimum_required(VERSION 3.5) # If CMAKE_PREFIX_PATH is not specified, provide a convenient default, so that the `find_package()` below can find # the Hyper API. This default assumes this `CMakeLists.txt` to be in its original location under `examples/`. if (NOT DEFINED CMAKE_PREFIX_PATH) get_filename_component(HAPI_PACKAGE_LOCATION "${CMAKE_SOURCE_DIR}/.." REALPATH) set(CMAKE_PREFIX_PATH "${HAPI_PACKAGE_LOCATION}/share/cmake" CACHE PATH "CMake prefix path" FORCE) endif () project("Tableau Hyper API for C++ Examples" LANGUAGES CXX) find_package(tableauhyperapi-cxx REQUIRED CONFIG) ``` -------------------------------- ### Examine Existing Hyper Database Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/hyper-jupyter-kernel/README.md SQL commands to attach a Hyper file and query its contents. ```sql \attach "data.hyper" database1 ``` ```sql SELECT * FROM "Extract"."Extract" LIMIT 1 ``` ```sql SELECT COUNT(*) FROM "Extract"."Extract" ``` -------------------------------- ### Import data from Pandas DataFrame Source: https://context7.com/tableau/hyper-api-samples/llms.txt Import data directly from a pandas DataFrame into a Hyper table by iterating over rows and using the Inserter class. Ensure pandas is installed and the DataFrame schema matches the target table. ```python from pathlib import Path import pandas as pd from tableauhyperapi import ( HyperProcess, Telemetry, Connection, CreateMode, NOT_NULLABLE, SqlType, TableDefinition, Inserter, HyperException ) ``` -------------------------------- ### Run Parquet Query on Google Storage Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/s3-compatible-services/README.md Execute a Python script to perform a live query on a Parquet file located in a public Google Cloud Storage bucket. Ensure Python 3.9+ and necessary dependencies are installed. ```bash $ python query-parquet-on-gs.py ``` -------------------------------- ### Display list command syntax Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/adjust-vertex-order/README.md Shows the arguments required to list tables and GEOGRAPHY columns. ```text usage: adjust_vertex_order.py list [-h] -i optional arguments: -h, --help show this help message and exit -i , --input_file Input .hyper file ``` -------------------------------- ### Connect to Hyper Files in Python Source: https://context7.com/tableau/hyper-api-samples/llms.txt Establishes a connection to a .hyper file using specific create modes and optional parameters. ```python from pathlib import Path from tableauhyperapi import HyperProcess, Telemetry, Connection, CreateMode path_to_database = Path("example.hyper") with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper: # Optional connection parameters connection_parameters = {"lc_time": "en_US"} # Create new file (or replace if exists) with Connection( endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE, parameters=connection_parameters ) as connection: print("Connected to Hyper file") # Access catalog for schema operations schemas = connection.catalog.get_schema_names() print(f"Schemas: {schemas}") # Open existing file (CreateMode.NONE) with Connection( endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.NONE ) as connection: print("Opened existing Hyper file") ``` -------------------------------- ### Create and Publish Hyper File to Tableau Server Source: https://context7.com/tableau/hyper-api-samples/llms.txt This script creates a Hyper file with sample customer data and then publishes it to Tableau Server or Tableau Online using a Personal Access Token for authentication. Ensure server configuration details and token values are correctly set. ```python from pathlib import Path import tableauserverclient as TSC from tableauhyperapi import ( HyperProcess, Telemetry, Connection, CreateMode, NOT_NULLABLE, SqlType, TableDefinition, Inserter, TableName, HyperException ) # Server configuration (use environment variables in production) server_address = 'https://your-server.online.tableau.com/' site_name = 'your-site' project_name = 'your-project' token_name = 'your-token-name' token_value = 'your-token-value' hyper_name = 'customer.hyper' path_to_database = Path(hyper_name) # Table definition extract_table = TableDefinition( table_name=TableName("Extract", "Extract"), columns=[ TableDefinition.Column(name='Customer ID', type=SqlType.text(), nullability=NOT_NULLABLE), TableDefinition.Column(name='Customer Name', type=SqlType.text(), nullability=NOT_NULLABLE), TableDefinition.Column(name='Loyalty Reward Points', type=SqlType.big_int(), nullability=NOT_NULLABLE), TableDefinition.Column(name='Segment', type=SqlType.text(), nullability=NOT_NULLABLE) ] ) def create_hyper_file(): """Create the Hyper file with sample data.""" with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper: with Connection( endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE ) as connection: connection.catalog.create_schema(schema=extract_table.table_name.schema_name) connection.catalog.create_table(table_definition=extract_table) data = [ ["DK-13375", "Dennis Kane", 685, "Consumer"], ["EB-13705", "Ed Braxton", 815, "Corporate"] ] with Inserter(connection, extract_table) as inserter: inserter.add_rows(rows=data) inserter.execute() row_count = connection.execute_scalar_query( f"SELECT COUNT(*) FROM {extract_table.table_name}" ) print(f"Created Hyper file with {row_count} rows") def publish_to_server(): """Publish the Hyper file to Tableau Server.""" # Authenticate with Personal Access Token tableau_auth = TSC.PersonalAccessTokenAuth( token_name=token_name, personal_access_token=token_value, site_id=site_name ) server = TSC.Server(server_address, use_server_version=True) print(f"Signing into {site_name} at {server_address}") with server.auth.sign_in(tableau_auth): # Find project ID project_id = None for project in TSC.Pager(server.projects): if project.name == project_name: project_id = project.id break if not project_id: raise ValueError(f"Project '{project_name}' not found") # Create datasource and publish datasource = TSC.DatasourceItem(project_id) # Publish modes: Overwrite, Append, CreateNew publish_mode = TSC.Server.PublishMode.Overwrite print(f"Publishing {hyper_name} to {project_name}...") datasource = server.datasources.publish( datasource, path_to_database, publish_mode ) print(f"Published! Datasource ID: {datasource.id}") # Run if __name__ == '__main__': create_hyper_file() publish_to_server() ``` -------------------------------- ### Configure Geospatial Data Insertion Sample Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Defines the executable and test environment for the geospatial data insertion sample. ```cmake add_executable(insert_geospatial_data_to_a_hyper_file insert_geospatial_data_to_a_hyper_file.cpp) target_link_libraries(insert_geospatial_data_to_a_hyper_file PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME insert_geospatial_data_to_a_hyper_file COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Display usage information for the adjust_vertex_order script Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/adjust-vertex-order/README.md Displays the available commands for the script. ```text usage: adjust_vertex_order.py [-h] {list,run} ... commands: {list,run} Available commands list Lists all tables in a .hyper file and shows columns of type GEOGRAPHY run Copies tables from a .hyper file to a new file while adjusting vertex order of all polygons ``` -------------------------------- ### Run Hyper file conversion via CLI Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/convert-hyper-file/README.md Execute the conversion script using the command line to specify output paths and target file versions. ```cli (venv)c:\mydir> python convert_hyper_file.py -o NewVersionFile.hyper -v 1 OldVersionFile.hyper Successfully converted table "input_database"."Extract"."Extract" Successfully converted OldVersionFile.hyper into NewVersionFile.hyper ``` -------------------------------- ### Configure Update Data Sample Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Defines the executable and test environment for the data update sample. ```cmake add_executable(update_data_in_existing_hyper_file update_data_in_existing_hyper_file.cpp) target_link_libraries(update_data_in_existing_hyper_file PRIVATE Tableau::tableauhyperapi-cxx) add_test( NAME update_data_in_existing_hyper_file COMMAND ${CMAKE_COMMAND} -E env HYPER_PATH=${HYPER_PATH} $ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) ``` -------------------------------- ### Execute the Hyper creation script Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/pandas-to-hyper/README.md Run the Python script to generate the .hyper file from the sample DataFrame. ```bash python create_hyper_from_pandas_dataframe.py ``` -------------------------------- ### PostgreSQL Connection Configuration Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Configure connection parameters for a PostgreSQL database. Verify these settings against your PostgreSQL instance. ```yaml postgres: connection: dbname : "dev" username : "test" password : "password" host : "postgres.test" port : 5432 ``` -------------------------------- ### Hyper CLI Convenience Commands Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/hyper-jupyter-kernel/README.md A collection of built-in commands for managing output streams, executing scripts, and handling Hyper file attachments. ```APIDOC ## Hyper CLI Commands ### Description Convenience functions for managing the current Hyper CLI session, including output redirection and file management. ### Commands - **\o ** - Redirects the output of all following queries to the specified file. - **\o -** - Discards the output of all following queries. - **\o** - Resets the output to display on the console. - **\i ** - Reads and executes a query from the specified file. - **\attach ** - Opens a Hyper file within the current session to access its tables. - **\detach ** - Closes a previously attached Hyper file. ``` -------------------------------- ### Clone Repository Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/clouddb-extractor/README.md Downloads the latest version of the Hyper API samples repository. ```console git clone https://github.com/tableau/hyper-api-samples.git ``` -------------------------------- ### Run list_hyper_contents.py script Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/list-hyper-contents/README.md Execute the script from the console, providing the path to the Hyper file as the sole argument. ```bash python list_hyper_contents.py my_data.hyper ``` -------------------------------- ### Insert Data into Tables Source: https://context7.com/tableau/hyper-api-samples/llms.txt Demonstrates creating a table and inserting both single and multiple rows using the Inserter class. ```python from pathlib import Path from datetime import datetime from tableauhyperapi import ( HyperProcess, Telemetry, Connection, CreateMode, NOT_NULLABLE, SqlType, TableDefinition, Inserter, TableName, HyperException ) # Define table schema extract_table = TableDefinition( table_name=TableName("Extract", "Extract"), columns=[ TableDefinition.Column(name='Customer ID', type=SqlType.text(), nullability=NOT_NULLABLE), TableDefinition.Column(name='Customer Name', type=SqlType.text(), nullability=NOT_NULLABLE), TableDefinition.Column(name='Loyalty Reward Points', type=SqlType.big_int(), nullability=NOT_NULLABLE), TableDefinition.Column(name='Segment', type=SqlType.text(), nullability=NOT_NULLABLE) ] ) path_to_database = Path("customer.hyper") try: with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper: with Connection( endpoint=hyper.endpoint, database=path_to_database, create_mode=CreateMode.CREATE_AND_REPLACE ) as connection: # Create schema and table connection.catalog.create_schema(schema=extract_table.table_name.schema_name) connection.catalog.create_table(table_definition=extract_table) # Data to insert data_to_insert = [ ["DK-13375", "Dennis Kane", 518, "Consumer"], ["EB-13705", "Ed Braxton", 815, "Corporate"] ] # Insert multiple rows with Inserter(connection, extract_table) as inserter: inserter.add_rows(rows=data_to_insert) inserter.execute() # Insert single row with Inserter(connection, extract_table) as inserter: inserter.add_row(row=["JH-13600", "Jane Howard", 950, "Home Office"]) inserter.execute() # Verify insertion row_count = connection.execute_scalar_query( query=f"SELECT COUNT(*) FROM {extract_table.table_name}" ) print(f"Rows in table: {row_count}") except HyperException as ex: print(f"Hyper error: {ex}") exit(1) ``` -------------------------------- ### Exemplary usage of list_hyper_contents.py Source: https://github.com/tableau/hyper-api-samples/blob/main/Community-Supported/list-hyper-contents/README.md Demonstrates the output when running the script with the 'World Indicators.hyper' file. Shows the number of schemas, tables per schema, and columns per table with their data types. ```bash python list_hyper_contents.py "World Indicators.hyper" ``` -------------------------------- ### Import from Parquet files using COPY command Source: https://context7.com/tableau/hyper-api-samples/llms.txt Import data from Apache Parquet files using the COPY command, which leverages the file's schema information for efficient columnar storage. ```python from pathlib import Path from tableauhyperapi import ( HyperProcess, Telemetry, Connection, CreateMode, NOT_NULLABLE, SqlType, TableDefinition, escape_string_literal, HyperException ) # Define table schema matching Parquet structure orders_table = TableDefinition( table_name="orders", columns=[ TableDefinition.Column("o_orderkey", SqlType.int(), NOT_NULLABLE), TableDefinition.Column("o_custkey", SqlType.int(), NOT_NULLABLE), TableDefinition.Column("o_orderstatus", SqlType.text(), NOT_NULLABLE), TableDefinition.Column("o_totalprice", SqlType.numeric(8, 2), NOT_NULLABLE), TableDefinition.Column("o_orderdate", SqlType.date(), NOT_NULLABLE), TableDefinition.Column("o_orderpriority", SqlType.text(), NOT_NULLABLE), TableDefinition.Column("o_clerk", SqlType.text(), NOT_NULLABLE), TableDefinition.Column("o_shippriority", SqlType.int(), NOT_NULLABLE), TableDefinition.Column("o_comment", SqlType.text(), NOT_NULLABLE), ] ) parquet_file_path = "orders_10rows.parquet" hyper_database_path = Path("orders.hyper") try: with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper: with Connection( endpoint=hyper.endpoint, database=hyper_database_path, create_mode=CreateMode.CREATE_AND_REPLACE ) as connection: # Create target table connection.catalog.create_table(table_definition=orders_table) # Copy from Parquet file copy_command = f"COPY {orders_table.table_name} FROM {escape_string_literal(parquet_file_path)} WITH (FORMAT PARQUET)" count_inserted = connection.execute_command(copy_command) print(f"Copied {count_inserted} rows from Parquet file") except HyperException as ex: print(f"Error: {ex}") ``` -------------------------------- ### Set C++ Standard and Enable Testing Source: https://github.com/tableau/hyper-api-samples/blob/main/Tableau-Supported/CPP/CMakeLists.txt Configures the C++ standard to C++11 and enables the testing framework for the project. This ensures compatibility and allows tests to be run. ```cmake set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) enable_testing() ``` -------------------------------- ### List Hyper File Contents with Python Source: https://context7.com/tableau/hyper-api-samples/llms.txt Uses the catalog API to iterate through schemas, tables, and column definitions. Requires a valid path to a .hyper file. ```python from pathlib import Path from tableauhyperapi import HyperProcess, Telemetry, Connection, CreateMode, Nullability def list_hyper_contents(hyper_file_path: str): """List all schemas, tables, and columns in a Hyper file.""" with HyperProcess(telemetry=Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper: with Connection(hyper.endpoint, hyper_file_path, CreateMode.NONE) as connection: catalog = connection.catalog # Get all schemas schemas = catalog.get_schema_names() print(f"{len(schemas)} schemas found:") for schema_name in schemas: # Get tables in each schema tables = catalog.get_table_names(schema=schema_name) print(f"\n Schema '{schema_name}': {len(tables)} tables") for table in tables: # Get table definition table_definition = catalog.get_table_definition(name=table) print(f"\n Table '{table.name}': {len(table_definition.columns)} columns") for column in table_definition.columns: nullability = "NOT NULL" if column.nullability == Nullability.NOT_NULLABLE else "NULLABLE" collation = f" COLLATE {column.collation}" if column.collation else "" print(f" - {column.name}: {column.type} {nullability}{collation}") # Usage list_hyper_contents("World Indicators.hyper") ```