From 2e3ab11115216999ef9e7f329e4f992d5b7f351d Mon Sep 17 00:00:00 2001 From: Dimitri Vorona Date: Mon, 7 Nov 2022 11:57:31 +0100 Subject: [PATCH] Add hyperapi-cli script to interactively run SQL commands --- Community-Supported/hyperapi-cli/README.md | 10 ++++++ .../hyperapi-cli/hyperapi-cli.py | 36 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 Community-Supported/hyperapi-cli/README.md create mode 100755 Community-Supported/hyperapi-cli/hyperapi-cli.py diff --git a/Community-Supported/hyperapi-cli/README.md b/Community-Supported/hyperapi-cli/README.md new file mode 100644 index 0000000..0f90db5 --- /dev/null +++ b/Community-Supported/hyperapi-cli/README.md @@ -0,0 +1,10 @@ +# hyperapi-cli +## An interactive HyperAPI SQL cli + +This script allows you to interactively execute SQL commands via HyperAPI. + +## Usage + +```bash +./hyperapi-cli.py [optional hyper database file] +``` \ No newline at end of file diff --git a/Community-Supported/hyperapi-cli/hyperapi-cli.py b/Community-Supported/hyperapi-cli/hyperapi-cli.py new file mode 100755 index 0000000..3805b45 --- /dev/null +++ b/Community-Supported/hyperapi-cli/hyperapi-cli.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +import readline +from argparse import ArgumentParser +from tableauhyperapi import HyperProcess, Connection, Telemetry, CreateMode, HyperException + + +def main(): + parser = ArgumentParser("HyperAPI interactive cli.") + parser.add_argument("database", type=str, nargs='?', + help="A Hyper file to attach on startup") + + args = parser.parse_args() + create_mode = CreateMode.CREATE_IF_NOT_EXISTS if args.database else CreateMode.NONE + + with HyperProcess(Telemetry.SEND_USAGE_DATA_TO_TABLEAU) as hyper_process: + try: + with Connection(hyper_process.endpoint, args.database, create_mode) as connection: + while True: + try: + sql = input("> ") + except (EOFError, KeyboardInterrupt): + return + try: + with connection.execute_query(sql) as result: + print("\t".join(str(column.name) + for column in result.schema.columns)) + for row in result: + print("\t".join(str(column) for column in row)) + except HyperException as exception: + print(f"Error executing SQL: {exception}") + except HyperException as exception: + print(f"Unable to connect to the database: {exception}") + + +if __name__ == "__main__": + main()