{"_id":"@ashmit_2k04/nlsql","name":"@ashmit_2k04/nlsql","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@ashmit_2k04/nlsql","version":"1.0.0","description":"Natural language SQL — query databases in plain English from the terminal","type":"module","bin":{"nlsql":"src/index.js"},"main":"./src/index.js","scripts":{"start":"node src/index.js","test":"node scripts/test.js","seed-demo":"node scripts/seed-demo.js","postinstall":"node scripts/postinstall.js","prepublishOnly":"npm test && node scripts/seed-demo.js"},"keywords":["sql","natural-language","cli","database","groq","postgres","mysql","sqlite","text-to-sql","nl2sql"],"license":"MIT","engines":{"node":">=18.0.0"},"publishConfig":{"access":"public"},"dependencies":{"better-sqlite3":"^12.11.1","chalk":"^5.6.2","cli-table3":"^0.6.5","commander":"^15.0.0","dotenv":"^17.4.2","groq-sdk":"^0.37.0","mysql2":"^3.22.4","ora":"^8.2.0","pg":"^8.21.0","xlsx":"^0.18.5"},"_id":"@ashmit_2k04/nlsql@1.0.0","gitHead":"be13fd1a8e353e3db7e032358d2433139191b446","_nodeVersion":"24.6.0","_npmVersion":"11.4.2","dist":{"integrity":"sha512-QXpsBjNvOwPleuyYvpggkZwGCfCvOMWGY+hQzJ4Iflh2hz58OJSl8guRwlYQDa4uIrNLnW9b2xX1a0JloDcCtw==","shasum":"f03810b673204ec5ecca85f06de35a8c1b961f7f","tarball":"https://registry.npmjs.org/@ashmit_2k04/nlsql/-/nlsql-1.0.0.tgz","fileCount":14,"unpackedSize":67085,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIHncwgtMRkDfoG7CoGcal/1/FGL0qAOzwXRtx/MuKPb/AiEAhSGS1aevk0uXcWEcd3D4yPf/GabNuvlydCR3/sI8eXU="}]},"_npmUser":{"name":"ashmit_2k04","email":"ashmit.rana2019@gmail.com"},"directories":{},"maintainers":[{"name":"ashmit_2k04","email":"ashmit.rana2019@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/nlsql_1.0.0_1781700894801_0.7772265458268428"},"_hasShrinkwrap":false}},"time":{"created":"2026-06-17T12:54:54.547Z","1.0.0":"2026-06-17T12:54:54.963Z","modified":"2026-06-17T12:54:55.574Z"},"maintainers":[{"name":"ashmit_2k04","email":"ashmit.rana2019@gmail.com"}],"description":"Natural language SQL — query databases in plain English from the terminal","keywords":["sql","natural-language","cli","database","groq","postgres","mysql","sqlite","text-to-sql","nl2sql"],"license":"MIT","readme":"# nlsql\n\n**Natural language SQL for the terminal.**\n\n`nlsql` translates plain-English questions into SQL, executes them against your database, and renders results as formatted tables — with optional Excel export. No SQL knowledge required.\n\nPowered by [Groq](https://groq.com) (Llama 3.3) with schema-aware generation, automatic query correction, and a bundled demo database so you can start immediately.\n\n```bash\nnlsql \"show all employees over 40 who missed their 2026 sales target\"\n```\n\n---\n\n## Table of contents\n\n- [Features](#features)\n- [Requirements](#requirements)\n- [Quick start](#quick-start)\n- [Installation](#installation)\n- [Configuration](#configuration)\n- [Usage](#usage)\n- [CLI reference](#cli-reference)\n- [Interactive mode](#interactive-mode)\n- [Database support](#database-support)\n- [Demo database](#demo-database)\n- [How it works](#how-it-works)\n- [Security](#security)\n- [Development](#development)\n- [Troubleshooting](#troubleshooting)\n- [License](#license)\n\n---\n\n## Features\n\n- **Natural language input** — ask questions in plain English, get executable SQL\n- **Zero database setup** — ships with a built-in SQLite demo database\n- **Multi-database support** — PostgreSQL, MySQL, and SQLite\n- **Schema introspection** — reads table structure, column types, and keys before generating queries\n- **Auto-correction** — retries failed queries by feeding errors back to the model\n- **Conversation context** — interactive mode supports follow-up questions\n- **Excel export** — export results to `.xlsx` with one flag\n- **Dry-run mode** — generate and inspect SQL without executing\n- **Global or project-scoped config** — works as a globally installed CLI or per-project tool\n\n---\n\n## Requirements\n\n| Dependency | Version |\n|------------|---------|\n| Node.js    | ≥ 18.0  |\n| Groq API key | [Free at console.groq.com](https://console.groq.com/keys) |\n\nOptional: Bun ≥ 1.0 (alternative package manager)\n\n---\n\n## Quick start\n\n### Add to your project (recommended)\n\n```bash\nnpm install nlsql\nnpx nlsql init          # creates .env — add your free Groq API key\nnpx nlsql demo          # try it instantly (built-in demo database)\nnpx nlsql \"top 5 customers by revenue\"\nnpx nlsql chat          # conversation mode with follow-ups\n```\n\nGet a free API key at [console.groq.com/keys](https://console.groq.com/keys).\n\n**Optional shortcuts** — add to your `package.json`:\n\n```json\n{\n  \"scripts\": {\n    \"ask\": \"nlsql\",\n    \"db:demo\": \"nlsql demo\",\n    \"db:chat\": \"nlsql chat\"\n  }\n}\n```\n\nThen run: `npm run db:demo` or `npm run ask -- \"how many employees are there?\"`\n\n### Global install\n\n```bash\nnpm install -g nlsql\nnlsql init\nnlsql demo\nnlsql \"top 5 customers by revenue\"\n```\n\nExpected output: a formatted terminal table with query results.\n\n---\n\n## Commands\n\n| Command | What it does |\n|---------|--------------|\n| `nlsql init` | Set up your project (creates `.env`) |\n| `nlsql demo` | Try nlsql with the built-in demo database |\n| `nlsql \"your question\"` | Ask a question in plain English |\n| `nlsql chat` | Conversation mode — follow-up questions |\n| `nlsql --help` | Show all options |\n\n---\n\n## Installation\n\n### In your project (recommended)\n\n```bash\nnpm install nlsql\nnpx nlsql init\nnpx nlsql demo\n```\n\n### Global install\n\n```bash\nnpm install -g nlsql\nnlsql init\n```\n\n### Bun\n\n```bash\nbun add nlsql\nbunx nlsql init\n```\n\n### Run without installing\n\n```bash\nnpx nlsql demo\nnpx nlsql \"how many employees are there?\"\n```\n\n### Verify installation\n\n```bash\nnlsql --version\nnlsql --help\nnlsql init\n```\n\n---\n\n## Configuration\n\n### Environment variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `GROQ_API_KEY` | Yes | — | Groq API key for SQL generation |\n| `NLSQL_DB` | No | bundled demo | Database connection string |\n| `DATABASE_URL` | No | — | Alternative to `NLSQL_DB` (Heroku/Railway convention) |\n| `NLSQL_MODEL` | No | `llama-3.3-70b-versatile` | Groq model override |\n\n### Config file locations\n\nEnvironment files are loaded from the first path that exists (later files do not override earlier values):\n\n1. `./.env` (current working directory)\n2. `./.nlsql` (current working directory)\n3. `~/.nlsql/.env` (user home — recommended for global installs)\n4. `~/.config/nlsql/.env` (XDG config directory)\n\n**Example: persistent global config**\n\n```bash\nmkdir -p ~/.nlsql\ncp .env.example ~/.nlsql/.env\n# Edit ~/.nlsql/.env and set GROQ_API_KEY\n```\n\n### Project config file\n\nCreate `.nlsql.json` in your project root to set a default database:\n\n```json\n{\n  \"db\": \"postgres://readonly:password@localhost:5432/production\"\n}\n```\n\n### Database connection priority\n\nWhen resolving which database to use, `nlsql` applies the following order (highest priority first):\n\n1. `--db` CLI flag\n2. `NLSQL_DB` environment variable\n3. `DATABASE_URL` environment variable\n4. `.nlsql.json` → `db` field\n5. Bundled demo database (`data/demo.sqlite`)\n\n---\n\n## Usage\n\n### Single query\n\n```bash\nnlsql \"employees over 40 in the sales department\"\n```\n\n### Show generated SQL\n\n```bash\nnlsql \"top 10 customers by revenue\" --show-sql\n```\n\n### Dry run (generate SQL only)\n\n```bash\nnlsql \"average sale amount per employee\" --dry-run\n```\n\n### Export to Excel\n\n```bash\nnlsql \"all sales in 2026\" --xlsx\nnlsql \"all sales in 2026\" --xlsx --out sales-report.xlsx\n```\n\n### Connect to your own database\n\n```bash\n# PostgreSQL\nnlsql \"active users last 30 days\" --db postgres://user:pass@localhost:5432/mydb\n\n# MySQL\nnlsql \"orders over $500\" --db mysql://user:pass@localhost:3306/shop\n\n# SQLite\nnlsql \"count rows in events\" --db /path/to/database.sqlite\n```\n\n### Combine flags\n\n```bash\nnlsql \"revenue by customer\" --db postgres://... --show-sql --xlsx --out revenue.xlsx\n```\n\n---\n\n## CLI reference\n\n```\nUsage: nlsql [command] [options] [query]\n\nCommands:\n  init                     Set up nlsql in your project (creates .env)\n  demo [query]             Try nlsql with the built-in demo database\n  chat                     Conversation mode with follow-up questions\n\nArguments:\n  query                    Natural language query\n\nOptions:\n  -V, --version            Output the current version\n  -d, --db <connection>    Database connection string (overrides config)\n  -x, --xlsx               Export results to Excel\n  -o, --out <file>         Output Excel filename (default: \"results.xlsx\")\n  -s, --show-sql           Print the generated SQL before running\n  -i, --interactive        Start interactive REPL mode\n  -c, --config <path>      Path to config file (default: \".nlsql.json\")\n  --dry-run                Generate SQL without executing\n  -h, --help               Display help\n```\n\n| Flag | Short | Description |\n|------|-------|-------------|\n| `--db` | `-d` | Database connection string; overrides all other DB config |\n| `--show-sql` | `-s` | Print generated SQL before execution |\n| `--xlsx` | `-x` | Export results to an Excel file |\n| `--out` | `-o` | Excel output filename (default: `results.xlsx`) |\n| `--dry-run` | | Generate SQL only; do not connect or execute |\n| `--interactive` | `-i` | Start interactive REPL |\n| `--config` | `-c` | Custom path to JSON config file |\n| `--version` | `-V` | Print package version |\n| `--help` | `-h` | Print usage information |\n\n---\n\n## Interactive mode\n\nStart a conversation for exploratory querying and follow-up questions:\n\n```bash\nnlsql chat\n# or\nnlsql -i\n```\n\n### REPL commands\n\n| Command | Description |\n|---------|-------------|\n| `:sql` | Toggle display of generated SQL |\n| `:xlsx` | Toggle Excel export for each query |\n| `:history` | Show session query history |\n| `:clear` | Clear conversation context (for follow-ups) |\n| `:exit` | Exit the REPL |\n\n### Follow-up queries\n\nInteractive mode maintains conversation context, so you can refine results iteratively:\n\n```\n❯ top 10 customers by revenue\n❯ now only show ones created in 2024\n❯ sort them alphabetically\n```\n\n---\n\n## Database support\n\n| Engine | Connection string format | Schema introspection | Execution |\n|--------|--------------------------|----------------------|-----------|\n| PostgreSQL | `postgres://user:pass@host:5432/db` | Full (tables, columns, keys, FKs) | Supported |\n| MySQL | `mysql://user:pass@host:3306/db` | Full (tables, columns, keys) | Supported |\n| SQLite | `/absolute/or/relative/path.sqlite` | Full (via `PRAGMA table_info`) | Supported |\n\nDialect is detected automatically from the connection string.\n\n---\n\n## Demo database\n\nIf no database is configured, `nlsql` uses a bundled SQLite database with sample business data.\n\n### Schema\n\n**`employees`**\n\n| Column | Type | Notes |\n|--------|------|-------|\n| `id` | INTEGER | Primary key |\n| `name` | TEXT | |\n| `age` | INTEGER | |\n| `department` | TEXT | e.g. Sales, Engineering |\n| `hire_date` | TEXT | ISO date |\n\n**`sales`**\n\n| Column | Type | Notes |\n|--------|------|-------|\n| `id` | INTEGER | Primary key |\n| `employee_id` | INTEGER | FK → `employees.id` |\n| `amount` | REAL | Sale value |\n| `sale_date` | TEXT | ISO date |\n\n**`sales_targets`**\n\n| Column | Type | Notes |\n|--------|------|-------|\n| `id` | INTEGER | Primary key |\n| `employee_id` | INTEGER | FK → `employees.id` |\n| `year` | INTEGER | Target year |\n| `target_amount` | REAL | Annual target |\n\n**`customers`**\n\n| Column | Type | Notes |\n|--------|------|-------|\n| `id` | INTEGER | Primary key |\n| `name` | TEXT | |\n| `revenue` | REAL | Total revenue |\n| `created_at` | TEXT | ISO date |\n\n### Example queries\n\n```bash\nnlsql \"employees over 40 in the sales department\"\nnlsql \"who missed their 2026 sales target\"\nnlsql \"top 5 customers by revenue\"\nnlsql \"total sales per employee in 2026\"\n```\n\n---\n\n## How it works\n\n```\n┌─────────────┐     ┌──────────────────┐     ┌─────────────┐\n│  Your query │────▶│ Schema           │────▶│ Groq API    │\n│  (English)  │     │ introspection    │     │ (Llama 3.3) │\n└─────────────┘     └──────────────────┘     └──────┬──────┘\n                                                    │\n                     ┌──────────────────┐           ▼\n                     │ Terminal table / │     ┌─────────────┐\n                     │ Excel export     │◀────│ SQL execute │\n                     └──────────────────┘     └──────┬──────┘\n                                                     │\n                                              ┌──────▼──────┐\n                                              │ Auto-fix on │\n                                              │ error (1x)  │\n                                              └─────────────┘\n```\n\n1. **Connect** — resolves database config and establishes a connection\n2. **Introspect** — reads schema metadata (tables, columns, types, constraints)\n3. **Generate** — sends schema + natural language query to Groq; receives SQL\n4. **Execute** — runs the generated SQL against your database\n5. **Correct** — on failure, sends the error back to the model and retries once\n6. **Render** — displays results as a formatted table (up to 200 rows shown)\n7. **Export** — optionally writes results to Excel\n\nOnly schema structure and your query text are sent to the Groq API. Database credentials and row data never leave your machine.\n\n---\n\n## Security\n\n### Data handling\n\n| Data | Sent to Groq API? |\n|------|-------------------|\n| Natural language query | Yes |\n| Database schema (table/column names, types) | Yes |\n| Database credentials | No — stays local |\n| Query result rows | No — stays local |\n\n### Recommendations\n\n- Use a **read-only database user** when connecting to production databases\n- Store API keys in environment variables or `~/.nlsql/.env`, never in source control\n- Review generated SQL with `--dry-run` or `--show-sql` before running against sensitive data\n- Generated queries are `SELECT`-only by default; destructive operations require explicit intent in the query\n\n### API key management\n\n```bash\n# Do not commit .env — use the provided template\ncp .env.example .env\n```\n\n`.env` is listed in `.gitignore` by default.\n\n---\n\n## Development\n\n### Local setup\n\n```bash\ngit clone <repository-url>\ncd nlsql\nnpm install\ncp .env.example .env\n# Set GROQ_API_KEY in .env\n```\n\n### Scripts\n\n| Command | Description |\n|---------|-------------|\n| `npm start` | Run CLI (`node src/index.js`) |\n| `npm test` | Run test suite |\n| `npm run seed-demo` | Regenerate the bundled demo database |\n\n### Project structure\n\n```\nnlsql/\n├── data/\n│   └── demo.sqlite       # Bundled demo database\n├── scripts/\n│   ├── seed-demo.js      # Demo DB generator\n│   └── test.js           # Test suite\n├── src/\n│   ├── index.js          # CLI entry point\n│   ├── ai.js             # Groq integration\n│   ├── config.js         # Environment loading\n│   ├── db.js             # Database drivers & schema introspection\n│   ├── demo-db.js        # Bundled demo DB resolution\n│   ├── display.js        # Terminal table rendering\n│   ├── export.js         # Excel export\n│   ├── interactive.js    # REPL mode\n│   └── query.js          # Query pipeline orchestration\n├── .env.example\n├── package.json\n└── README.md\n```\n\n### Publishing\n\n```bash\nnpm test\nnpm login\nnpm publish\n```\n\nThe `prepublishOnly` hook runs tests and regenerates the demo database automatically.\n\n---\n\n## Troubleshooting\n\n### `No API key found. Set GROQ_API_KEY`\n\nSet the key via environment variable or config file:\n\n```bash\nexport GROQ_API_KEY=gsk_your_key_here\n```\n\nOr create `~/.nlsql/.env` with `GROQ_API_KEY=...`.\n\n### `Failed to generate SQL` / rate limits\n\nGroq free tier has request limits. Wait a moment and retry, or check usage at [console.groq.com](https://console.groq.com).\n\n### Query returns wrong results\n\n- Use `--show-sql` to inspect the generated SQL\n- Use `--dry-run` to validate SQL before execution\n- Ensure schema introspection succeeded (no connection errors during startup)\n- In interactive mode, use `:clear` to reset context if follow-ups drift\n\n### Cannot connect to database\n\n- Verify the connection string format for your database engine\n- Confirm the database server is running and reachable\n- Test connectivity with a native client (`psql`, `mysql`, etc.)\n- For SQLite, use an absolute path if relative paths fail\n\n### `nlsql` command not found after global install\n\nEnsure npm global bin is on your `PATH`:\n\n```bash\nnpm config get prefix\n# Add <prefix>/bin to your PATH\n```\n\n---\n\n## License\n\nMIT\n","readmeFilename":"README.md","_rev":"1-27a357111483b510fd6498bccfab8d75"}