{"repo": "alphavie/human-sql", "files": {"README.md": {"272be649a79e7ae5190b8146438a46f3b0901ab0": {"t": 1785746436.0453393, "n": 12382, "h": "fdaeaa749a6214a0", "c": "# human-sql 🧠🗄️\n\nQuery any SQL database in plain human language — powered by AI.\n\n```bash\nnpm install human-sql\n```\n\nWorks with **Prisma (v5, v6, v7+)**, **Drizzle ORM**, or a raw **`DATABASE_URL`** — no configuration required beyond your `.env`. Supports **JavaScript and TypeScript** out of the box.\n\n---\n\n## Table of Contents\n\n- [How It Works](#how-it-works)\n- [Requirements](#requirements)\n- [Setup](#setup)\n - [AI Provider](#ai-provider)\n - [Database](#database)\n- [Usage](#usage)\n - [Raw SQL](#raw-sql-no-orm)\n - [With Prisma](#with-prisma-v5-v6-v7)\n - [With Drizzle ORM](#with-drizzle-orm)\n - [TypeScript](#typescript)\n - [Express.js](#expressjs)\n - [Next.js App Router](#nextjs-app-router)\n - [Nuxt.js](#nuxtjs)\n - [Dry Run](#dry-run--inspect-generated-code)\n- [Options Reference](#options-reference)\n- [Environment Variables](#environment-variables)\n- [Supported Databases](#supported-databases)\n- [AI Providers](#ai-providers)\n- [Auto-Detection Logic](#auto-detection-logic)\n- [Error Handling & Self-Correction](#error-handling--self-correction)\n- [Troubleshooting](#troubleshooting)\n\n---\n\n## How It Works\n\n1. **Detects** your setup automatically — reads your `prisma/schema.prisma`, `drizzle.config.js`, or `DATABASE_URL` from `.env`\n2. **Extracts** your database schema — tables, columns, types, and foreign keys (from the schema file or via live DB introspection)\n3. **Sends** your natural language query + schema to the AI\n4. **Executes** the generated Prisma call, Drizzle query, or raw SQL against your database\n5. **Auto-retries** up to 3 times if the AI generates invalid code — the error is sent back so the AI can self-correct\n\n---\n\n## Requirements\n\n- Node.js **≥ 18**\n- An API key for an OpenAI-compatible AI provider (OpenAI, OpenRouter, DeepSeek, Azure, Ollama, etc.)\n- One of: a Prisma schema, a Drizzle config, or a database URL\n\n---\n\n## Setup\n\n### AI Provider\n\nAdd the following to your `.env`:\n\n```env\n# required — your API key\nHUMANSQL_API_KEY=sk-...\n\n# optional — AI model to use (default: gpt-4o)\nHUMANSQL_MODEL=gpt-4o\n\n# optional — base URL of the AI API (default: https://api.openai.com/v1)\nHUMANSQL_OPEN_AI_URL=https://api.openai.com/v1\n```\n\nhuman-sql works with any OpenAI-compatible API. See [AI Providers](#ai-providers) for examples.\n\n### Database\n\nhuman-sql auto-detects your database from your project. Depending on your setup, add one of the following to your `.env`:\n\n**PostgreSQL:**\n\n```env\nDATABASE_URL=postgresql://user:password@localhost:5432/mydb\n```\n\n**MySQL:**\n\n```env\nDATABASE_URL=mysql://user:password@localhost:3306/mydb\n```\n\n**SQLite:**\n\n```env\nDATABASE_URL=file:./dev.db\n```\n\n---\n\n## Usage\n\n### Raw SQL (no ORM)\n\n```js\nconst humanSql = require(\"human-sql\");\n\nconst { result, generatedCode } = await humanSql(\n \"get all users who placed at least 2 orders, sorted by name\",\n);\n\nconsole.log(generatedCode);\n// SELECT u.* FROM users u\n// JOIN orders o ON o.user_id = u.id\n// GROUP BY u.id, u.name\n// HAVING COUNT(o.id) >= 2\n// ORDER BY u.name\n\nconsole.log(result);\n// [{ id: 1, name: \"Alice\", email: \"alice@example.com\" }, ...]\n```\n\n---\n\n### With Prisma (v5, v6, v7+)\n\nhuman-sql supports all modern Prisma versions. It reads your `prisma/schema.prisma` automatically and detects the installed version to generate version-appropriate code.\n\n**Install:**\n\n```bash\nnpm install human-sql @prisma/client\n```\n\n**Usage:**\n\n```js\nconst humanSql = require(\"human-sql\");\nconst { PrismaClient } = require(\"@prisma/client\");\n\nconst prisma = new PrismaClient();\n\nconst { result, generatedCode } = await humanSql(\n \"get all orders from the last 30 days including the user and items\",\n { prismaClient: prisma },\n);\n\nconsole.log(generatedCode);\n// prisma.order.findMany({\n// where: { createdAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } },\n// include: { user: true, items: true }\n// })\n\nawait prisma.$disconnect();\n```\n\n**Prisma version compatibility:**\n\n| Version | Supported | Notes |\n| -------- | --------- | ----------------------------------------------------- |\n| Prisma 5 | ✅ | |\n| Prisma 6 | ✅ | |\n| Prisma 7 | ✅ | Version auto-detected, AI prompt adjusted accordingly |\n\n---\n\n### With Drizzle ORM\n\n**Install:**\n\n```bash\nnpm install human-sql drizzle-orm pg\n```\n\n**Usage:**\n\n```js\nconst humanSql = require(\"human-sql\");\nconst { db } = require(\"./lib/db\");\nconst schema = require(\"./lib/schema\");\n\nconst { result } = await humanSql(\"top 5 customers by total order value\", {\n drizzleClient: db,\n drizzleSchema: schema,\n});\n```\n\nMake sure your schema exports all tables at the top level:\n\n```js\n// lib/schema.js\nconst { pgTable, serial, text, integer } = require(\"drizzle-orm/pg-core\");\n\nconst users = pgTable(\"users\", {\n id: serial(\"id\").primaryKey(),\n name: text(\"name\"),\n});\nconst orders = pgTable(\"orders\", {\n id: serial(\"id\").primaryKey(),\n userId: integer(\"user_id\").references(() => users.id),\n});\n\nmodule.exports = { users, orders };\n```\n\n---\n\n### TypeScript\n\nhuman-sql ships with full TypeScript type definitions — no `@types/` package needed.\n\n```ts\nimport humanSql, { HumanSqlOptions, HumanSqlResult } from \"human-sql\";\nimport { PrismaClient } from \"@prisma/client\";\n\nconst prisma = new PrismaClient();\n\nconst options: HumanSqlOptions = { prismaClient: prisma };\n\nconst { result, generatedCode }: HumanSqlResult = await humanSql(\n \"get all users with more than 3 orders\",\n options,\n);\n```\n\n---\n\n### Express.js\n\n```js\nconst express = require(\"express\");\nconst humanSql = require(\"human-sql\");\nconst { PrismaClient } = require(\"@prisma/client\");\n\nconst app = express();\nconst prisma = new PrismaClient();\napp.use(express.json());\n\napp.post(\"/api/query\", async (req, res) => {\n const { query } = req.body;\n if (!query) return res.status(400).json({ error: \"query is required\" });\n try {\n const { result, generatedCode } = await humanSql(query, {\n prismaClient: prisma,\n });\n res.json({ result, generatedCode });\n } catch (err) {\n res.status(500).json({ error: err.message });\n }\n});\n\napp.listen(3000);\n```\n\n---\n\n### Next.js (App Router)\n\n```ts\n// app/api/query/route.ts\nimport humanSql from \"human-sql\";\nimport { prisma } from \"@/lib/prisma\";\n\nexport async function POST(req: Request) {\n const { query } = await req.json();\n try {\n const { result, generatedCode } = await humanSql(query, {\n prismaClient: prisma,\n });\n return Response.json({ result, generatedCode });\n } catch (err: any) {\n return Response.json({ error: err.message }, { status: 500 });\n }\n}\n```\n\n> Place your `HUMANSQL_API_KEY` and database URL in `.env.local` for Next.js projects.\n\n---\n\n### Nuxt.js\n\n```ts\n// server/api/query.post.ts\nimport humanSql from \"human-sql\";\n\nexport default defineEventHandler(async (event) => {\n const { query } = await readBody(event);\n const { result, generatedCode } = await humanSql(query);\n return { result, generatedCode };\n});\n```\n\n---\n\n### Dry Run — inspect generated code\n\n```js\nconst { generatedCode, result } = await humanSql(\n \"delete all users who have never placed an order\",\n { dryRun: true },\n);\n\nconsole.log(generatedCode); // DELETE FROM users WHERE id NOT IN (SELECT DISTINCT user_id FROM orders)\nconsole.log(result); // null — nothing was executed\n```\n\n---\n\n## Options Reference\n\n| Option | Type | Default | Description |\n| --------------- | --------------- | --------------- | ------------------------------------------------------------ |\n| `cwd` | `string` | `process.cwd()` | Working directory used for ORM and `.env` detection |\n| `prismaClient` | `PrismaClient` | — | Your Prisma client instance (required when using Prisma) |\n| `drizzleClient` | `DrizzleClient` | — | Your Drizzle client instance (required when using Drizzle) |\n| `drizzleSchema` | `object` | — | All your Drizzle table exports (required when using Drizzle) |\n| `schemaPath` | `string` | auto | Manual path to your schema file — overrides auto-detection |\n| `dryRun` | `boolean` | `false` | If `true`, returns generated code without executing |\n| `forceOrm` | `object` | auto | Fully override ORM auto-detection |\n\n---\n\n## Environment Variables\n\n| Variable | Required | Default | Description |\n| ---------------------- | -------- | --------------------------- | ---------------------------- |\n| `HUMANSQL_API_KEY` | ✅ | — | API key for your AI provider |\n| `HUMANSQL_MODEL` | ❌ | `gpt-4o` | Model name to use |\n| `HUMANSQL_OPEN_AI_URL` | ❌ | `https://api.openai.com/v1` | Base URL of the AI API |\n| `DATABASE_URL` | ✅\\* | — | Database connection string |\n| `POSTGRES_URL` | ✅\\* | — | Alternative for PostgreSQL |\n| `MYSQL_URL` | ✅\\* | — | Alternative for MySQL |\n| `SQLITE_URL` | ✅\\* | — | Alternative for SQLite |\n\n\\* One database URL is required when not using Prisma or Drizzle.\n\n---\n\n## Supported Databases\n\n| Database | Raw SQL | Prisma | Drizzle | Required package |\n| ---------- | ------- | ------ | ------- | ---------------- |\n| PostgreSQL | ✅ | ✅ | ✅ | `pg` |\n| MySQL | ✅ | ✅ | ✅ | `mysql2` |\n| SQLite | ✅ | ✅ | ✅ | `better-sqlite3` |\n| MSSQL | — | ✅ | — | — |\n\n---\n\n## AI Providers\n\n**OpenAI (default):**\n\n```env\nHUMANSQL_API_KEY=sk-...\nHUMANSQL_MODEL=gpt-4o\n```\n\n**OpenRouter:**\n\n```env\nHUMANSQL_API_KEY=sk-or-...\nHUMANSQL_MODEL=deepseek/deepseek-chat\nHUMANSQL_OPEN_AI_URL=https://openrouter.ai/api/v1/chat/completions\n```\n\n**DeepSeek:**\n\n```env\nHUMANSQL_API_KEY=sk-...\nHUMANSQL_MODEL=deepseek-chat\nHUMANSQL_OPEN_AI_URL=https://api.deepseek.com/v1\n```\n\n**Azure OpenAI:**\n\n```env\nHUMANSQL_API_KEY=your-azure-key\nHUMANSQL_MODEL=gpt-4o\nHUMANSQL_OPEN_AI_URL=https://YOUR_RESOURCE.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT/chat/completions?api-version=2024-02-15-preview\n```\n\n**Ollama (local, free):**\n\n```env\nHUMANSQL_API_KEY=ollama\nHUMANSQL_MODEL=llama3\nHUMANSQL_OPEN_AI_URL=http://localhost:11434/v1\n```\n\n---\n\n## Auto-Detection Logic\n\nWhen you call `humanSql()`, it scans your project in this order:\n\n1. **Prisma** — looks for `prisma/schema.prisma` or `schema.prisma`\n2. **Drizzle** — looks for `drizzle.config.js/ts` or a schema file that imports `drizzle-orm`\n3. **Database URL** — reads `DATABASE_URL`, `POSTGRES_URL`, `MYSQL_URL`, or `SQLITE_URL` from `.env`\n\nThe first match wins. You can override detection with `forceOrm` or `schemaPath`.\n\n---\n\n## Error Handling & Self-Correction\n\nIf the AI generates invalid code, human-sql automatically sends the error message back to the AI and asks it to correct the code — up to **3 attempts** total.\n\n```js\ntry {\n const { result } = await humanSql(\"your query\", { prismaClient: prisma });\n} catch (err) {\n // only thrown after all 3 attempts failed\n console.error(\"could not generate valid code:\", err.message);\n}\n```\n\n---\n\n## Troubleshooting\n\n**`HUMANSQL_API_KEY is not set`**\nAdd `HUMANSQL_API_KEY=your-key` to your `.env` file in the project root.\n\n**`No database configuration found`**\nMake sure one of the following exists in your project root:\n\n- `prisma/schema.prisma`\n- `drizzle.config.js`\n- `DATABASE_URL` in `.env`\n\n**`\"pg\" is required for PostgreSQL`**\nInstall the missing driver: `npm install pg`\n\n**AI generates wrong table/column names**\nThe AI only knows what's in your schema. Make sure it's accurate and up to date — e.g. run `npx prisma db push` if using Prisma.\n\n**Prisma: `Argument 'not' must not be null`**\nKnown AI mistake — the self-correction loop will automatically retry and fix it.\n\n**Drizzle: `column must appear in GROUP BY`**\nThe retry loop catches this. If it fails repeatedly, try rephrasing your query to be more specific.\n\n---\n\n## License\n\nMIT © [AlphaVIE](https://github.com/AlphaVIE)\n"}, "b5e121d445d458fbe7bd18d5b2678510f1b584b4": {"t": 1785764189.0546782, "n": 12484, "h": "71c01eb770f218a8", "c": "# human-sql 🧠🗄️\n\nQuery any SQL database in plain human language — powered by AI.\n\n```bash\nnpm install human-sql\n```\n\nWorks with **Prisma (v5, v6, v7+)**, **Drizzle ORM**, or a raw **`DATABASE_URL`** — no configuration required beyond your `.env`. Supports **JavaScript and TypeScript** out of the box.\n\n---\n\n## Table of Contents\n\n- [How It Works](#how-it-works)\n- [Requirements](#requirements)\n- [Setup](#setup)\n - [AI Provider](#ai-provider)\n - [Database](#database)\n- [Usage](#usage)\n - [Raw SQL](#raw-sql-no-orm)\n - [With Prisma](#with-prisma-v5-v6-v7)\n - [With Drizzle ORM](#with-drizzle-orm)\n - [TypeScript](#typescript)\n - [Express.js](#expressjs)\n - [Next.js App Router](#nextjs-app-router)\n - [Nuxt.js](#nuxtjs)\n - [Dry Run](#dry-run--inspect-generated-code)\n- [Options Reference](#options-reference)\n- [Environment Variables](#environment-variables)\n- [Supported Databases](#supported-databases)\n- [AI Providers](#ai-providers)\n- [Auto-Detection Logic](#auto-detection-logic)\n- [Error Handling & Self-Correction](#error-handling--self-correction)\n- [Troubleshooting](#troubleshooting)\n\n---\n\n## How It Works\n\n1. **Detects** your setup automatically — reads your `prisma/schema.prisma`, `drizzle.config.js`, or `DATABASE_URL` from `.env`\n2. **Extracts** your database schema — tables, columns, types, and foreign keys (from the schema file or via live DB introspection)\n3. **Sends** your natural language query + schema to the AI\n4. **Executes** the generated Prisma call, Drizzle query, or raw SQL against your database\n5. **Auto-retries** up to 3 times if the AI generates invalid code — the error is sent back so the AI can self-correct\n\n---\n\n## Requirements\n\n- Node.js **≥ 18**\n- An API key for an OpenAI-compatible AI provider (OpenAI, OpenRouter, DeepSeek, Azure, Ollama, etc.)\n- One of: a Prisma schema, a Drizzle config, or a database URL\n\n---\n\n## Setup\n\n### AI Provider\n\nAdd the following to your `.env`:\n\n```env\n# required — your API key\nHUMANSQL_API_KEY=sk-...\n\n# optional — AI model to use (default: gpt-4o)\nHUMANSQL_MODEL=gpt-4o\n\n# optional — base URL of the AI API (default: https://api.openai.com/v1)\nHUMANSQL_OPEN_AI_URL=https://api.openai.com/v1\n```\n\nhuman-sql works with any OpenAI-compatible API. See [AI Providers](#ai-providers) for examples.\n\n### Database\n\nhuman-sql auto-detects your database from your project. Depending on your setup, add one of the following to your `.env`:\n\n**PostgreSQL:**\n```env\nDATABASE_URL=postgresql://user:password@localhost:5432/mydb\n```\n\n**MySQL:**\n```env\nDATABASE_URL=mysql://user:password@localhost:3306/mydb\n```\n\n**SQLite:**\n```env\nDATABASE_URL=file:./dev.db\n```\n\n---\n\n## Usage\n\n### Raw SQL (no ORM)\n\n```js\nconst humanSql = require(\"human-sql\");\n\nconst { result, generatedCode } = await humanSql(\n \"get all users who placed at least 2 orders, sorted by name\"\n);\n\nconsole.log(generatedCode);\n// SELECT u.* FROM users u\n// JOIN orders o ON o.user_id = u.id\n// GROUP BY u.id, u.name\n// HAVING COUNT(o.id) >= 2\n// ORDER BY u.name\n\nconsole.log(result);\n// [{ id: 1, name: \"Alice\", email: \"alice@example.com\" }, ...]\n```\n\n---\n\n### With Prisma (v5, v6, v7+)\n\nhuman-sql supports all modern Prisma versions. It reads your `prisma/schema.prisma` automatically and detects the installed version to generate version-appropriate code.\n\n**Install:**\n```bash\nnpm install human-sql @prisma/client\n```\n\n**Usage:**\n```js\nconst humanSql = require(\"human-sql\");\nconst { PrismaClient } = require(\"@prisma/client\");\n\nconst prisma = new PrismaClient();\n\nconst { result, generatedCode } = await humanSql(\n \"get all orders from the last 30 days including the user and items\",\n { prismaClient: prisma }\n);\n\nconsole.log(generatedCode);\n// prisma.order.findMany({\n// where: { createdAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) } },\n// include: { user: true, items: true }\n// })\n\nawait prisma.$disconnect();\n```\n\n**Prisma version compatibility:**\n\n| Version | Supported | Notes |\n|----------|-----------|---------------------------------------------------------------|\n| Prisma 5 | ✅ | |\n| Prisma 6 | ✅ | |\n| Prisma 7 | ✅ | Version auto-detected, AI prompt adjusted accordingly |\n\n---\n\n### With Drizzle ORM\n\n**Install:**\n```bash\nnpm install human-sql drizzle-orm pg\n```\n\n**Usage:**\n```js\nconst humanSql = require(\"human-sql\");\nconst { db } = require(\"./lib/db\");\nconst schema = require(\"./lib/schema\");\n\nconst { result } = await humanSql(\"top 5 customers by total order value\", {\n drizzleClient: db,\n drizzleSchema: schema,\n});\n```\n\nMake sure your schema exports all tables at the top level:\n\n```js\n// lib/schema.js\nconst { pgTable, serial, text, integer } = require(\"drizzle-orm/pg-core\");\n\nconst users = pgTable(\"users\", {\n id: serial(\"id\").primaryKey(),\n name: text(\"name\"),\n});\nconst orders = pgTable(\"orders\", {\n id: serial(\"id\").primaryKey(),\n userId: integer(\"user_id\").references(() => users.id),\n});\n\nmodule.exports = { users, orders };\n```\n\n---\n\n### TypeScript\n\nhuman-sql ships with full TypeScript type definitions — no `@types/` package needed.\n\n```ts\nimport humanSql, { HumanSqlOptions, HumanSqlResult } from \"human-sql\";\nimport { PrismaClient } from \"@prisma/client\";\n\nconst prisma = new PrismaClient();\n\nconst options: HumanSqlOptions = { prismaClient: prisma };\n\nconst { result, generatedCode }: HumanSqlResult = await humanSql(\n \"get all users with more than 3 orders\",\n options\n);\n```\n\n---\n\n### Express.js\n\n```js\nconst express = require(\"express\");\nconst humanSql = require(\"human-sql\");\nconst { PrismaClient } = require(\"@prisma/client\");\n\nconst app = express();\nconst prisma = new PrismaClient();\napp.use(express.json());\n\napp.post(\"/api/query\", async (req, res) => {\n const { query } = req.body;\n if (!query) return res.status(400).json({ error: \"query is required\" });\n try {\n const { result, generatedCode } = await humanSql(query, { prismaClient: prisma });\n res.json({ result, generatedCode });\n } catch (err) {\n res.status(500).json({ error: err.message });\n }\n});\n\napp.listen(3000);\n```\n\n---\n\n### Next.js (App Router)\n\n```ts\n// app/api/query/route.ts\nimport humanSql from \"human-sql\";\nimport { prisma } from \"@/lib/prisma\";\n\nexport async function POST(req: Request) {\n const { query } = await req.json();\n try {\n const { result, generatedCode } = await humanSql(query, { prismaClient: prisma });\n return Response.json({ result, generatedCode });\n } catch (err: any) {\n return Response.json({ error: err.message }, { status: 500 });\n }\n}\n```\n\n> Place your `HUMANSQL_API_KEY` and database URL in `.env.local` for Next.js projects.\n\n---\n\n### Nuxt.js\n\n```ts\n// server/api/query.post.ts\nimport humanSql from \"human-sql\";\n\nexport default defineEventHandler(async (event) => {\n const { query } = await readBody(event);\n const { result, generatedCode } = await humanSql(query);\n return { result, generatedCode };\n});\n```\n\n---\n\n### Dry Run — inspect generated code\n\n```js\nconst { generatedCode, result } = await humanSql(\n \"delete all users who have never placed an order\",\n { dryRun: true }\n);\n\nconsole.log(generatedCode); // DELETE FROM users WHERE id NOT IN (SELECT DISTINCT user_id FROM orders)\nconsole.log(result); // null — nothing was executed\n```\n\n---\n\n## Options Reference\n\n| Option | Type | Default | Description |\n|-----------------|-----------------|------------------|----------------------------------------------------------|\n| `cwd` | `string` | `process.cwd()` | Working directory used for ORM and `.env` detection |\n| `prismaClient` | `PrismaClient` | — | Your Prisma client instance (required when using Prisma) |\n| `drizzleClient` | `DrizzleClient` | — | Your Drizzle client instance (required when using Drizzle) |\n| `drizzleSchema` | `object` | — | All your Drizzle table exports (required when using Drizzle) |\n| `schemaPath` | `string` | auto | Manual path to your schema file — overrides auto-detection |\n| `dryRun` | `boolean` | `false` | If `true`, returns generated code without executing |\n| `forceOrm` | `object` | auto | Fully override ORM auto-detection |\n\n---\n\n## Environment Variables\n\n| Variable | Required | Default | Description |\n|----------------------|--------------|-------------------------------|--------------------------------------|\n| `HUMANSQL_API_KEY` | ✅ | — | API key for your AI provider |\n| `HUMANSQL_MODEL` | ❌ | `gpt-4o` | Model name to use |\n| `HUMANSQL_OPEN_AI_URL` | ❌ | `https://api.openai.com/v1` | Base URL of the AI API |\n| `DATABASE_URL` | ✅* | — | Database connection string |\n| `POSTGRES_URL` | ✅* | — | Alternative for PostgreSQL |\n| `MYSQL_URL` | ✅* | — | Alternative for MySQL |\n| `SQLITE_URL` | ✅* | — | Alternative for SQLite |\n\n\\* One database URL is required when not using Prisma or Drizzle.\n\n---\n\n## Supported Databases\n\n| Database | Raw SQL | Prisma | Drizzle | Required package |\n|------------|---------|--------|---------|--------------------|\n| PostgreSQL | ✅ | ✅ | ✅ | `pg` |\n| MySQL | ✅ | ✅ | ✅ | `mysql2` |\n| SQLite | ✅ | ✅ | ✅ | `better-sqlite3` |\n| MSSQL | — | ✅ | — | — |\n\n---\n\n## AI Providers\n\n**OpenAI (default):**\n```env\nHUMANSQL_API_KEY=sk-...\nHUMANSQL_MODEL=gpt-4o\n```\n\n**OpenRouter:**\n```env\nHUMANSQL_API_KEY=sk-or-...\nHUMANSQL_MODEL=deepseek/deepseek-chat\nHUMANSQL_OPEN_AI_URL=https://openrouter.ai/api/v1/chat/completions\n```\n\n**DeepSeek:**\n```env\nHUMANSQL_API_KEY=sk-...\nHUMANSQL_MODEL=deepseek-chat\nHUMANSQL_OPEN_AI_URL=https://api.deepseek.com/v1\n```\n\n**Azure OpenAI:**\n```env\nHUMANSQL_API_KEY=your-azure-key\nHUMANSQL_MODEL=gpt-4o\nHUMANSQL_OPEN_AI_URL=https://YOUR_RESOURCE.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT/chat/completions?api-version=2024-02-15-preview\n```\n\n**Ollama (local, free):**\n```env\nHUMANSQL_API_KEY=ollama\nHUMANSQL_MODEL=llama3\nHUMANSQL_OPEN_AI_URL=http://localhost:11434/v1\n```\n\n---\n\n## Auto-Detection Logic\n\nWhen you call `humanSql()`, it scans your project in this order:\n\n1. **Prisma** — looks for `prisma/schema.prisma` or `schema.prisma`\n2. **Drizzle** — looks for `drizzle.config.js/ts` or a schema file that imports `drizzle-orm`\n3. **Database URL** — reads `DATABASE_URL`, `POSTGRES_URL`, `MYSQL_URL`, or `SQLITE_URL` from `.env`\n\nThe first match wins. You can override detection with `forceOrm` or `schemaPath`.\n\n---\n\n## Error Handling & Self-Correction\n\nIf the AI generates invalid code, human-sql automatically sends the error message back to the AI and asks it to correct the code — up to **3 attempts** total.\n\n```js\ntry {\n const { result } = await humanSql(\"your query\", { prismaClient: prisma });\n} catch (err) {\n // only thrown after all 3 attempts failed\n console.error(\"could not generate valid code:\", err.message);\n}\n```\n\n---\n\n## Troubleshooting\n\n**`HUMANSQL_API_KEY is not set`**\nAdd `HUMANSQL_API_KEY=your-key` to your `.env` file in the project root.\n\n**`No database configuration found`**\nMake sure one of the following exists in your project root:\n- `prisma/schema.prisma`\n- `drizzle.config.js`\n- `DATABASE_URL` in `.env`\n\n**`\"pg\" is required for PostgreSQL`**\nInstall the missing driver: `npm install pg`\n\n**AI generates wrong table/column names**\nThe AI only knows what's in your schema. Make sure it's accurate and up to date — e.g. run `npx prisma db push` if using Prisma.\n\n**Prisma: `Argument 'not' must not be null`**\nKnown AI mistake — the self-correction loop will automatically retry and fix it.\n\n**Drizzle: `column must appear in GROUP BY`**\nThe retry loop catches this. If it fails repeatedly, try rephrasing your query to be more specific.\n\n---\n\n## License\n\nMIT © [AlphaVIE](https://github.com/AlphaVIE)\n"}, "1b6157f43a964a8bbc2690882990d9143f4a58ca": {"t": 1785764192.3323863, "n": 4679, "h": "5395884653fce440", "c": "# human-sql 🧠🗄️\n\nQuery any SQL database in plain human language — powered by AI. \nWorks with **Prisma**, **Drizzle ORM**, or a raw **`DATABASE_URL`** — no config required.\n\n```bash\nnpm install human-sql\n```\n\n---\n\n## Setup\n\nAdd the following to your `.env`:\n\n```env\nHUMANSQL_API_KEY=sk-... # required — OpenAI or compatible API key\nHUMANSQL_MODEL=gpt-4o # optional — default: gpt-4o\nHUMANSQL_OPEN_AI_URL=... # optional — default: https://api.openai.com/v1\n```\n\nWorks with any OpenAI-compatible provider: OpenRouter, Azure OpenAI, Ollama, DeepSeek, etc.\n\n---\n\n## Usage\n\n### Raw SQL (no ORM needed)\n\n```js\nconst humanSql = require(\"human-sql\");\n\nconst { result, generatedCode } = await humanSql(\n \"get all users who placed at least 2 orders\",\n);\n\nconsole.log(generatedCode); // SELECT u.* FROM users u JOIN ...\nconsole.log(result); // [{ id: 1, name: \"Alice\", ... }, ...]\n```\n\nJust set `DATABASE_URL` (or `POSTGRES_URL` / `MYSQL_URL` / `SQLITE_URL`) in your `.env` — human-sql auto-detects the dialect and introspects your schema.\n\n---\n\n### With Prisma\n\n```js\nconst humanSql = require(\"human-sql\");\nconst { PrismaClient } = require(\"@prisma/client\");\n\nconst prisma = new PrismaClient();\n\nconst { result } = await humanSql(\"get all active products sorted by price\", {\n prismaClient: prisma,\n});\n```\n\n---\n\n### With Drizzle ORM\n\n```js\nconst humanSql = require(\"human-sql\");\nconst { db } = require(\"./lib/drizzle\");\nconst schema = require(\"./lib/schema\");\n\nconst { result } = await humanSql(\"top 5 customers by total order value\", {\n drizzleClient: db,\n drizzleSchema: schema,\n});\n```\n\n---\n\n### Express.js\n\n```js\nconst express = require(\"express\");\nconst humanSql = require(\"human-sql\");\n\nconst app = express();\napp.use(express.json());\n\napp.post(\"/query\", async (req, res) => {\n try {\n const result = await humanSql(req.body.query);\n res.json({ success: true, data: result });\n } catch (err) {\n res.status(500).json({ success: false, error: err.message });\n }\n});\n```\n\n---\n\n### Next.js (App Router)\n\n```js\n// app/api/query/route.js\nimport humanSql from \"human-sql\";\n\nexport async function POST(req) {\n const { query } = await req.json();\n const result = await humanSql(query);\n return Response.json({ data: result });\n}\n```\n\n---\n\n## Options\n\n| Option | Type | Description |\n| --------------- | --------------- | -------------------------------------------------------------- |\n| `cwd` | `string` | Working directory for ORM detection (default: `process.cwd()`) |\n| `prismaClient` | `PrismaClient` | Your Prisma client instance |\n| `drizzleClient` | `DrizzleClient` | Your Drizzle client instance |\n| `drizzleSchema` | `object` | Your Drizzle schema (all table exports) |\n| `schemaPath` | `string` | Manual path to schema file (overrides auto-detection) |\n| `dryRun` | `boolean` | Return generated code without executing it |\n| `forceOrm` | `object` | Fully override ORM auto-detection |\n\n---\n\n## Environment Variables\n\n| Variable | Required | Default |\n| ------------------------------------------------------------ | -------------- | --------------------------- |\n| `HUMANSQL_API_KEY` | ✅ | — |\n| `HUMANSQL_MODEL` | ❌ | `gpt-4o` |\n| `HUMANSQL_OPEN_AI_URL` | ❌ | `https://api.openai.com/v1` |\n| `DATABASE_URL` / `POSTGRES_URL` / `MYSQL_URL` / `SQLITE_URL` | ✅ (if no ORM) | — |\n\n---\n\n## How It Works\n\n1. **Detects** your setup — Prisma schema, Drizzle config, or `DATABASE_URL` in `.env`\n2. **Extracts** your schema — tables, columns, relations (via file or live DB introspection)\n3. **Sends** your natural language query + schema to the AI\n4. **Executes** the generated code against your database\n5. **Auto-retries** up to 3 times if the AI generates invalid code, feeding the error back for self-correction\n\n---\n\n## Supported Databases\n\n| Database | Raw SQL | Prisma | Drizzle |\n| ---------- | ------- | ------ | ------- |\n| PostgreSQL | ✅ | ✅ | ✅ |\n| MySQL | ✅ | ✅ | ✅ |\n| SQLite | ✅ | ✅ | ✅ |\n| MSSQL | ✅ | ✅ | ❌ |\n\n---\n\n## License\n\nMIT © [AlphaVIE](https://github.com/AlphaVIE)\n"}}}}