Metadata-Version: 2.4
Name: teshq
Version: 3.0.0.dev1
Summary: A CLI tool that converts natural language queries into SQL and returns relevant tables using natural language.
Author-email: Shashank <shashankgundas1@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2025-2026 Shashank Gundas
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/theshashank1/TESH-Query
Project-URL: Bug Tracker, https://github.com/theshashank1/TESH-Query/issues
Project-URL: Documentation, https://github.com/theshashank1/TESH-Query#readme
Keywords: sql,cli,database,natural language,AI,LLM
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: SQLAlchemy<3.0,>=2.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: langchain>=0.3
Requires-Dist: langchain-core>=0.3
Requires-Dist: langchain-google-genai>=2.0
Requires-Dist: typer<1.0,>=0.9
Requires-Dist: rich<15.0,>=13.0
Requires-Dist: prompt-toolkit>=3.0.38
Requires-Dist: logfire>=2.0
Requires-Dist: tabulate>=0.9
Requires-Dist: pandas>=2.0
Requires-Dist: openpyxl>=3.1.0
Requires-Dist: pyyaml~=6.0
Requires-Dist: pydantic~=2.0
Requires-Dist: pydantic-settings~=2.0
Requires-Dist: email-validator>=2.0.0
Requires-Dist: requests>=2.31.0
Requires-Dist: sqlparse>=0.4.4
Requires-Dist: tomli>=2.0.0; python_version < "3.11"
Requires-Dist: langchain-openai>=0.2
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=1.0; extra == "dev"
Requires-Dist: autopep8>=2.0; extra == "dev"
Requires-Dist: pre-commit>=3.0; extra == "dev"
Requires-Dist: flake8>=6.0; extra == "dev"
Requires-Dist: isort>=5.12; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: mkdocs-material; extra == "dev"
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.29; extra == "postgres"
Provides-Extra: postgres-binary
Requires-Dist: psycopg2-binary>=2.9; extra == "postgres-binary"
Provides-Extra: mysql
Requires-Dist: PyMySQL>=1.1; extra == "mysql"
Requires-Dist: mysql-connector-python>=8.4; extra == "mysql"
Provides-Extra: mariadb
Requires-Dist: PyMySQL>=1.0; extra == "mariadb"
Provides-Extra: mariadb-native
Requires-Dist: mariadb>=1.1; extra == "mariadb-native"
Provides-Extra: mssql
Requires-Dist: pymssql>=2.2; extra == "mssql"
Provides-Extra: mssql-odbc
Requires-Dist: pyodbc>=4.0; extra == "mssql-odbc"
Provides-Extra: oracle
Requires-Dist: oracledb>=2.0; extra == "oracle"
Provides-Extra: cassandra
Requires-Dist: cassandra-driver>=3.29; extra == "cassandra"
Provides-Extra: bigquery
Requires-Dist: sqlalchemy-bigquery>=1.11.0; extra == "bigquery"
Requires-Dist: google-cloud-bigquery>=3.25.0; extra == "bigquery"
Provides-Extra: snowflake
Requires-Dist: snowflake-sqlalchemy>=1.6.0; extra == "snowflake"
Requires-Dist: snowflake-connector-python>=3.12.0; extra == "snowflake"
Provides-Extra: databricks
Requires-Dist: databricks-sql-connector>=3.0.0; extra == "databricks"
Provides-Extra: redshift
Requires-Dist: sqlalchemy-redshift>=0.8.0; extra == "redshift"
Provides-Extra: duckdb
Requires-Dist: duckdb-engine>=0.13.0; extra == "duckdb"
Requires-Dist: duckdb>=1.1.0; extra == "duckdb"
Provides-Extra: clickhouse
Requires-Dist: clickhouse-connect>=0.7.0; extra == "clickhouse"
Requires-Dist: clickhouse-sqlalchemy>=0.3.0; extra == "clickhouse"
Provides-Extra: analytics
Requires-Dist: duckdb-engine>=0.13.0; extra == "analytics"
Requires-Dist: duckdb>=1.1.0; extra == "analytics"
Requires-Dist: sqlalchemy-bigquery>=1.11.0; extra == "analytics"
Requires-Dist: snowflake-sqlalchemy>=1.6.0; extra == "analytics"
Provides-Extra: export
Requires-Dist: openpyxl>=3.1; extra == "export"
Provides-Extra: langsmith
Requires-Dist: langsmith>=0.1; extra == "langsmith"
Provides-Extra: local
Requires-Dist: llama-cpp-python>=0.3.0; extra == "local"
Provides-Extra: data
Requires-Dist: pyarrow>=14.0; extra == "data"
Requires-Dist: polars>=0.20; extra == "data"
Provides-Extra: ml
Requires-Dist: pyarrow>=14.0; extra == "ml"
Requires-Dist: polars>=0.20; extra == "ml"
Requires-Dist: duckdb>=1.1.0; extra == "ml"
Provides-Extra: all
Requires-Dist: PyMySQL>=1.1; extra == "all"
Requires-Dist: mysql-connector-python>=8.4; extra == "all"
Requires-Dist: pymssql>=2.2; extra == "all"
Requires-Dist: openpyxl>=3.1; extra == "all"
Requires-Dist: mkdocs-material; extra == "all"
Provides-Extra: all-native
Requires-Dist: PyMySQL>=1.1; extra == "all-native"
Requires-Dist: mysql-connector-python>=8.4; extra == "all-native"
Requires-Dist: mariadb>=1.1; extra == "all-native"
Requires-Dist: pyodbc>=4.0; extra == "all-native"
Requires-Dist: pymssql>=2.2; extra == "all-native"
Requires-Dist: oracledb>=2.0; extra == "all-native"
Requires-Dist: openpyxl>=3.1; extra == "all-native"
Requires-Dist: mkdocs-material; extra == "all-native"
Provides-Extra: all-databases
Requires-Dist: PyMySQL>=1.1; extra == "all-databases"
Requires-Dist: mysql-connector-python>=8.4; extra == "all-databases"
Requires-Dist: oracledb>=2.0; extra == "all-databases"
Requires-Dist: cassandra-driver>=3.29; extra == "all-databases"
Requires-Dist: sqlalchemy-bigquery>=1.11.0; extra == "all-databases"
Requires-Dist: snowflake-sqlalchemy>=1.6.0; extra == "all-databases"
Requires-Dist: duckdb-engine>=0.13.0; extra == "all-databases"
Requires-Dist: clickhouse-connect>=0.7.0; extra == "all-databases"
Requires-Dist: sqlalchemy-redshift>=0.8.0; extra == "all-databases"
Requires-Dist: databricks-sql-connector>=3.0.0; extra == "all-databases"
Provides-Extra: all-features
Requires-Dist: PyMySQL>=1.1; extra == "all-features"
Requires-Dist: mysql-connector-python>=8.4; extra == "all-features"
Requires-Dist: oracledb>=2.0; extra == "all-features"
Requires-Dist: cassandra-driver>=3.29; extra == "all-features"
Requires-Dist: sqlalchemy-bigquery>=1.11.0; extra == "all-features"
Requires-Dist: snowflake-sqlalchemy>=1.6.0; extra == "all-features"
Requires-Dist: duckdb-engine>=0.13.0; extra == "all-features"
Requires-Dist: clickhouse-connect>=0.7.0; extra == "all-features"
Requires-Dist: sqlalchemy-redshift>=0.8.0; extra == "all-features"
Requires-Dist: databricks-sql-connector>=3.0.0; extra == "all-features"
Requires-Dist: langsmith>=0.1; extra == "all-features"
Dynamic: license-file

<div align="center">

# TESH-Query

**Autonomous Natural Language to SQL Execution & Safety Harness**

[![PyPI version](https://img.shields.io/pypi/v/teshq?color=blue)](https://pypi.org/project/teshq/)
[![Python Support](https://img.shields.io/pypi/pyversions/teshq)](https://pypi.org/project/teshq/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![CI/CD](https://github.com/theshashank1/TESH-Query/actions/workflows/deploy_teshq.yaml/badge.svg)](https://github.com/theshashank1/TESH-Query/actions/workflows/deploy_teshq.yaml)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

[Quick Start](#quick-start) • [Interactive Terminal](#interactive-terminal-teshq-chat) • [Local Offline Mode](#100-offline--air-gapped-mode-local-gguf) • [CLI Reference](#cli-reference) • [Python SDK](#python-sdk) • [Architecture](#the-harness-architecture)

</div>

---

**TESH-Query (TESHQ)** is a production-grade text-to-SQL compiler and execution harness. It translates plain English into dialect-accurate, injection-safe SQL across 11+ databases, validates queries via an AST firewall, and self-heals syntax errors in an automated closed loop.

Whether through the **interactive terminal (`teshq chat`)**, **scriptable CLI**, or **zero-copy Python SDK (Polars / PyArrow / Pandas)**, TESH-Query mediates the entire lifecycle between LLMs and production databases.

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  TESHQ HUD  •  PostgreSQL Connected (14ms)  •  Gemini 2.0  •  42 Tables    │
├─────────────────────────────────────────────────────────────────────────────┤
│  › top 10 products by revenue in 2024                                       │
│  [1/6] Schema Context  ✓ Top-4 tables pruned via TF-IDF                     │
│  [2/6] Query Planning  ✓ Identified INNER JOIN orders ON products.id        │
│  [3/6] SQL Synthesis   ✓ Compiled PostgreSQL dialect with :named params     │
│  [4/6] AST Firewall    ✓ Passed (Read-only SELECT, 0 destructive tokens)    │
│  [5/6] DB Execution    ✓ 10 rows returned in 18ms                           │
│  [6/6] Output Delivery ✓ Rendered tabular view                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## Key Features

- **Precision Interactive Terminal (`teshq chat`)** — Ambient status HUD, 6-stage cognitive progress tracker, and slash commands (`/tables`, `/copy`, `/model`, `/export`, `/explain`).
- **100% Offline & Air-Gapped Mode** — Run locally with GGUF models via `llama.cpp` and hardware acceleration (CUDA, Metal, CPU). Enforces **GBNF context-free grammar** to physically constrain LLM tokens to valid SQL.
- **AST Security Firewall** — Parses the Abstract Syntax Tree before execution. Hard-blocks destructive operations (`DROP`, `TRUNCATE`, `ALTER`, `CREATE`, `REPLACE`, and unconstrained `DELETE`/`UPDATE`).
- **TF-IDF Schema Vector Pruner** — Uses in-memory TF-IDF cosine similarity to index and extract only the 3–5 relevant tables from 100+ table databases, preventing context window overflow and slashing token costs.
- **Closed-Loop Self-Healing** — Intercepts database dialect errors, re-prompts the model with compiler feedback, and repairs SQL automatically with exponential backoff.
- **Zero-Copy Modern Analytics SDK** — First-class outputs for **Polars** (`result.polars`), **Apache Arrow** (`result.arrow`), and **Pandas** (`result.dataframe`), plus Parquet and JSONL exports.
- **Stateful Multi-Turn Sessions** — Context-aware follow-up queries (`"now filter by west region"`) that automatically thread previous SQL context.
- **11+ Database Dialects** — Native connectors for Cloud Data Warehouses (Snowflake, BigQuery, Databricks, Redshift), Real-Time OLAP (DuckDB, ClickHouse), Relational (PostgreSQL, MySQL, MSSQL, Oracle, SQLite), and NoSQL (Cassandra).

---

## The Harness Architecture

A raw LLM cannot safely query a production database. TESH-Query operates as a complete execution and safety harness:

```
 User Question: "Show active customers with orders > $1,000"
                       │
                       ▼
 ┌───────────────────────────────────────────┐
 │ 1. Schema Introspection & Graph Indexing  │  Extracts PK/FK relationships into SchemaGraph
 └─────────────────────┬─────────────────────┘
                       ▼
 ┌───────────────────────────────────────────┐
 │ 2. In-Memory TF-IDF Schema Retriever      │  Prunes 100+ tables down to Top-K relevant tables
 └─────────────────────┬─────────────────────┘
                       ▼
 ┌───────────────────────────────────────────┐
 │ 3. Two-Stage LLM Compiler                 │  Stage 1: Query Planner (tables, joins, filters)
 │                                           │  Stage 2: Dialect Generator (Gemini / Azure / GGUF)
 └─────────────────────┬─────────────────────┘
                       ▼
 ┌───────────────────────────────────────────┐
 │ 4. AST Security Firewall                  │  Blocks DROP, ALTER, TRUNCATE, injection
 └─────────────────────┬─────────────────────┘
                       ▼
 ┌───────────────────────────────────────────┐
 │ 5. Execution & Dialect Driver             │  Executes with bound parameters (:named)
 └─────────────────────┬─────────────────────┘
                       │
        ┌──────────────┴──────────────┐
        ▼                             ▼
 [Syntax Error?]              [Query Success]
 Capture error code,                  │
 re-feed into LLM,                    ▼
 self-heal & retry            DataFrame / Arrow / Polars
```

---

## Quick Start

### 1. Installation

Requires Python 3.10+.

```bash
# Core package (SQLite + Google Gemini out of the box)
pip install teshq

# Or install with specific database drivers
pip install "teshq[postgres]"    # PostgreSQL (asyncpg)
pip install "teshq[mysql]"       # MySQL / MariaDB (PyMySQL)
pip install "teshq[mssql]"       # Microsoft SQL Server (pymssql)
pip install "teshq[data]"        # High-performance Polars & PyArrow
pip install "teshq[local]"       # Offline GGUF inference (llama-cpp-python)
pip install "teshq[all]"         # All pure-Python drivers & tools
```

### 2. 30-Second Guided Configuration

Run the interactive Quick Setup Wizard:

```bash
teshq config --wizard
```

Or configure components directly:

```bash
# Configure your database connection
teshq config --db

# Choose your AI provider:
teshq config --gemini            # Google Gemini API key
teshq config --azure             # Azure OpenAI credentials
teshq config --local             # Local offline GGUF model
```

*All settings and credentials are encrypted/stored locally at `~/.teshq/`.*

### 3. Introspect Schema

Scan tables, columns, primary keys, and foreign-key relationships into the local graph cache:

```bash
teshq db introspect
```

### 4. Query Your Data

Launch the interactive terminal:

```bash
teshq chat
```

Or run a single query directly:

```bash
teshq query "Show monthly revenue by product category for Q3"
```

---

## Interactive Terminal (`teshq chat`)

`teshq chat` (alias: `teshq repl`) provides a dedicated conversational REPL designed for iterative data exploration.

```bash
teshq chat
```

### In-Session Slash Commands

| Command | Action |
| :--- | :--- |
| `/help` or `/?` | Open the interactive command palette |
| `/tables` or `/schema` | Display an ASCII visual tree of all tables and columns |
| `/sql` | Inspect the last generated SQL query with bound parameters |
| `/explain` | Ask the AI to explain the query plan, business logic, and joins |
| `/export csv [file]` | Export current results to CSV (auto-resolves filename if omitted) |
| `/export excel [file]`| Export current results to Excel (`.xlsx`) |
| `/export sqlite [file]`| Save current results directly into a SQLite database |
| `/copy sql` | Copy generated SQL directly to the system clipboard (Windows, macOS, Linux) |
| `/copy results` | Copy formatted results table to the system clipboard |
| `/model [name]` | Hot-swap active LLM provider live in session (`google`, `azure`, `local`) |
| `/clear` or `/cls` | Clear terminal screen and restore the ambient HUD |
| `/history` | View recent prompts executed during this session |
| `exit` or `quit` | Exit session with runtime statistics (queries, latency, tokens) |

---

## 100% Offline & Air-Gapped Mode (Local GGUF)

For zero-data-leak environments, TESH-Query can run entirely on your local machine with no external network calls.

### 1. Check Hardware Acceleration

```bash
teshq local status
```

Inspects your CPU threads, system RAM, and detects available GPU acceleration (NVIDIA CUDA or Apple Silicon Metal).

### 2. Manage & Download Models

TESH-Query includes an automated Hugging Face GGUF model manager:

```bash
# List recommended models and local download status
teshq model list

# Download recommended model (downloads to ~/.teshq/models/ with progress bar)
teshq model download qwen3b-coder
```

| Model | Parameters | Quantization | Recommended RAM | Description |
| :--- | :---: | :---: | :---: | :--- |
| `qwen1.5b-coder` | 1.5B | Q4_K_M | 6 GB | Ultra-lightweight; runs on low-end machines and laptops |
| `qwen3b-coder` | 3.0B | Q4_K_M | 8 GB | **Recommended** sweet spot for speed and accuracy |
| `qwen7b-coder` | 7.0B | Q4_K_M | 16 GB | High-accuracy SQL generation for complex multi-join schemas |

### 3. GBNF Grammar Enforcement

Local models are physically constrained at the token sampling level by [sql_grammar.gbnf](teshq/core/sql_grammar.gbnf). The model cannot emit arbitrary text or hallucinations; it is mathematically forced to generate syntactically valid SQL statements.

---

## CLI Reference

### `teshq query`

Convert a natural language prompt into SQL and execute it.

```bash
teshq query [OPTIONS] [REQUEST]
```

*If `REQUEST` is omitted, TESHQ launches an interactive prompt.*

| Flag | Description |
| :--- | :--- |
| `--dry-run` | Generate and validate SQL, but **do not execute** it |
| `-i, --confirm` | Interactively inspect and confirm generated SQL before running |
| `--explain` | Print execution plan, selected tables, SQL, and timing breakdown |
| `-n, --limit <N>` | Append `LIMIT N` to the generated SQL |
| `--save-csv <FILE>` | Save query results to a CSV file |
| `--save-excel <FILE>` | Save query results to an Excel spreadsheet (`.xlsx`) |
| `--save-sqlite <FILE>` | Save query results to a SQLite table |
| `--schema-preview` | Print the exact TF-IDF compressed schema sent to the LLM, then exit |
| `--full-schema` | Use verbose schema (including row counts and index metadata) |
| `--local` | Force local GGUF model inference for this query |
| `--cloud` | Force cloud LLM inference (Gemini or Azure) for this query |
| `--verbose` | Write detailed execution logs to `~/.teshq/logs/` |

**Examples:**

```bash
# Dry run: check generated SQL without executing
teshq query "Which customers have overdue invoices?" --dry-run

# Export results directly to Excel
teshq query "Top 20 sales representatives by deal value" --save-excel sales_q3.xlsx

# Interactive review mode before execution
teshq query "Update inventory counts for inactive items" -i
```

---

### Other Core Commands

| Command | Usage | Description |
| :--- | :--- | :--- |
| `teshq config` | `teshq config --wizard` | Interactive configuration wizard (DB + AI in 30 seconds) |
| `teshq config validate`| `teshq config validate` | Validate database connectivity, pooling, and production readiness |
| `teshq db explore` | `teshq db explore` | Interactive visual schema explorer |
| `teshq db show-schema` | `teshq db show-schema` | Display cached database schema |
| `teshq db clear-cache` | `teshq db clear-cache` | Reset cached schema in `~/.teshq/schemas/` |
| `teshq health` | `teshq health` | Run end-to-end diagnostics (DB ping, config, LLM latency) |
| `teshq bench run` | `teshq bench run` | Run Text-to-SQL benchmark suite measuring accuracy and cost |
| `teshq analytics` | `teshq analytics --days 7` | View token consumption and estimated query costs |

---

## Python SDK

TESH-Query provides a high-performance, asynchronous Python SDK for data analysts, data engineers, and machine learning pipelines.

### 1. Basic & Analytical Querying

```python
import teshq

# Initialize client (Zero-config connection pooling)
client = teshq.TeshQuery(
    db_url="postgresql://user:pass@localhost:5432/analytics_db",
    gemini_api_key="your-gemini-api-key"
)

# Compile schema locally (runs once, cached to ~/.teshq/)
client.introspect_database()


# 1. Natural language query returning Pandas DataFrame
df = client.query("Show weekly active users for past 6 months")

# 2. Native High-Performance Polars DataFrame (Zero-copy)
polars_df = client.query_polars("Monthly churn rate by plan tier")

# 3. Apache Arrow Table (Interoperable with PyData, DuckDB, Parquet)
arrow_table = client.query_arrow("Top 100 products by inventory turnover")
```

### 2. Multi-Turn Conversational Sessions

`TeshChatSession` maintains conversational memory and automatically stitches context for follow-up prompts:

```python
session = client.create_session()

# Turn 1: Initial query
df1 = session.ask("Show top 5 sales reps by total revenue")

# Turn 2: Automatic follow-up context threading!
df2 = session.ask("filter by west region only and sort descending")

# Inspect session state & export history
print(session.last_sql)
session_json = session.export_json()
```

### 3. Asynchronous Execution & Real-Time Event Streaming

```python
import asyncio

# Non-blocking async execution
async def run_pipeline():
    result = await client.aquery("Calculate customer lifetime value by acquisition cohort")
    print(result)

# Real-time lifecycle event streaming
for event in client.stream_query("Summarize quarterly revenue growth"):
    # event.stage: "schema_pruning", "planning", "sql_gen", "validation", "execution"
    print(f"[{event.stage}] {event.message}")
```

### 4. Bring-Your-Own-Engine (BYOE) & Business Context

Pass custom connection pools, SSL certificates, IAM authentication tokens, and business definitions directly:

```python
from sqlalchemy import create_engine
import teshq

custom_engine = create_engine(
    "postgresql://user:pass@db:5432/prod",
    pool_size=20,
    max_overflow=10,
    connect_args={"sslmode": "verify-full"}
)

client = teshq.TeshQuery(
    engine=custom_engine,  # Pass pre-configured engine
    business_context={
        "mrr": "SUM(amount) WHERE plan_type != 'trial' AND status = 'active'",
        "churned_user": "users with no login activity in 60 days"
    },
    gemini_api_key="your-api-key"
)
```

### 5. Advanced Query Results & Pagination

```python
result = client.query_advanced("SELECT department, headcount FROM company_stats")

# Pagination for large result sets
page_1 = result.paginate(page=1, page_size=25)
print(f"Page {page_1['page']} of {page_1['total_pages']} (Total rows: {page_1['total_rows']})")

# Export directly to Parquet or JSONL
result.to_parquet("company_stats.parquet")
result.to_jsonl("company_stats.jsonl")

# Structured payload with automatic chart recommendation hints (bar, line, scatter)
payload = result.to_payload()
print(payload["chart_hints"])  # e.g., {'type': 'bar', 'x_axis': 'department', 'y_axis': 'headcount'}
```

---

## Supported Databases & Dialects

TESH-Query speaks your database's exact SQL dialect:

| Category | Database | Driver / Extra | Dialect Features Supported |
| :--- | :--- | :--- | :--- |
| **Cloud Warehouses** | **Snowflake** | `snowflake-sqlalchemy` | Native Snowflake dialect, case-sensitive identifiers |
| | **Google BigQuery** | `sqlalchemy-bigquery` | Google Standard SQL, backtick quoting |
| | **Databricks** | `databricks-sql-connector` | Spark SQL dialect, Delta Lake catalogs |
| | **Amazon Redshift** | `sqlalchemy-redshift` | Redshift dialect, distkey/sortkey aware |
| **Real-Time OLAP** | **DuckDB** | `duckdb-engine` | In-process vectorized analytics, Parquet/CSV scanning |
| | **ClickHouse** | `clickhouse-connect` | ClickHouse SQL, specialized aggregations |
| **Relational** | **PostgreSQL** | `teshq[postgres]` (`asyncpg`) | CTEs, Window functions, JSONB operators |
| | **MySQL / MariaDB** | `teshq[mysql]` (`PyMySQL`) | Backtick escaping, MySQL 8.0+ window functions |
| | **Microsoft SQL Server** | `teshq[mssql]` (`pymssql`) | T-SQL dialect, `TOP` syntax, `@@VERSION` diagnostics |
| | **Oracle** | `oracledb` | PL/SQL, ROWNUM pagination |
| | **SQLite** | Built-in | Zero-config, in-memory or file-based |
| **NoSQL** | **Apache Cassandra** | `cassandra-driver` | CQL (Cassandra Query Language) |

---

## Installation Extras Reference

Install only what you need:

```bash
# Data science & high-performance analytics
pip install "teshq[data]"           # pyarrow, polars

# Machine learning & local OLAP
pip install "teshq[ml]"             # pyarrow, polars, duckdb

# Database drivers
pip install "teshq[postgres]"       # Pure-Python asyncpg (Python 3.10–3.14+)
pip install "teshq[postgres-binary]"# psycopg2-binary
pip install "teshq[mysql]"          # PyMySQL & mysql-connector-python
pip install "teshq[mssql]"          # pymssql (MS SQL Server)

# Offline local inference
pip install "teshq[local]"          # llama-cpp-python

# Comprehensive driver bundles
pip install "teshq[all]"            # All pre-built drivers (MySQL, MSSQL, Excel)
pip install "teshq[all-databases]"  # All database drivers (Cloud Warehouses + Relational)
```

---

## Verification & Diagnostics

TESH-Query includes an automated self-test and verification suite:

```bash
# Run complete system diagnostic health check
teshq health

# Run configuration and production readiness assessment
teshq config validate

# Run unit and integration tests (319 tests)
pytest tests/unit/
```

---

## Contributing

We welcome contributions! Please review [CONTRIBUTING.md](CONTRIBUTING.md) and our [Contributor License Agreement (CLA)](CLA.md).

```bash
# 1. Clone repository
git clone https://github.com/theshashank1/TESH-Query.git
cd TESH-Query

# 2. Install editable package with dev dependencies
pip install -e ".[dev]"

# 3. Run test suite
pytest tests/unit/
```

---

## License

TESH-Query is open-source software licensed under the **Apache License, Version 2.0**. See the [LICENSE](LICENSE) file for the full text.

```
Copyright 2025-2026 Shashank Gundas

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

---

<div align="center">
<sub>Built with precision by <a href="https://github.com/theshashank1">Shashank</a> • <a href="https://github.com/theshashank1/TESH-Query/issues">Report an issue</a> • <a href="https://github.com/theshashank1/TESH-Query/discussions">Join discussions</a></sub>
</div>
