{"slug": "use-case-a-text-to-sql-agent-that-queries-a-read-only-copy-in-a-sandbox", "title": "Use case: a text-to-SQL agent that queries a read-only copy in a sandbox", "summary": "A developer published a text-to-SQL agent pattern that runs model-generated SQL against a disposable read-only copy of a database inside a Sandscale sandbox, keeping the production database out of reach. The agent, built on the Vercel AI SDK with OpenAI's gpt-4.1, exposes a single run_sql tool that caps results at 200 rows and returns JSON, while the Python runner opens SQLite with mode=ro and PRAGMA query_only so writes fail with \"attempt to write a readonly database.", "body_md": "Text-to-SQL is one of the most useful things to put in front of a model, and one of the easiest to get wrong. The usual risks:\n\n`DELETE` or `UPDATE`, through a prompt injection or a plain mistake.\nThis use case answers questions over a **copy** of the data, in a [Sandscale sandbox](https://sandscale.dev/sandboxes), opened read-only. The production database never sees the model's SQL.\n\n`run_sql`, that runs a query against the copy in read-only mode and returns at most 200 rows as JSON.\nUses the Vercel AI SDK for the tool loop. Type-checked with `tsc --strict` against `ai` 7, `@ai-sdk/openai`, `zod` 4 and `@sandscale/sdk` 1.0. The Python runner inside the sandbox was tested separately against a SQLite file: `SELECT` returns columns and rows, more than 200 rows sets `truncated`, and a `DELETE` fails with \"attempt to write a readonly database\".\n\n``` js\nimport { generateText, tool, isStepCount } from 'ai';\nimport { openai } from '@ai-sdk/openai';\nimport { readFile } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { Sandscale } from '@sandscale/sdk';\n\nconst sandscale = new Sandscale(); // reads SANDSCALE_API_KEY\n\n// Runs inside the sandbox. Opens the database read-only, caps rows, prints JSON.\nconst RUNNER = `\nimport json, sqlite3, sys\nsql = open('/workspace/query.sql').read()\ncon = sqlite3.connect('file:/workspace/db.sqlite?mode=ro', uri=True)\ncon.execute('PRAGMA query_only = ON')\ncur = con.execute(sql)\ncols = [d[0] for d in cur.description or []]\nrows = cur.fetchmany(201)\nprint(json.dumps({\"columns\": cols, \"rows\": rows[:200], \"truncated\": len(rows) > 200}, default=str))\n`;\n\nexport async function askDatabase(question: string, sqlitePath: string) {\n  const sb = await sandscale.sandboxes.create({\n    template: 'builtin:python',\n    timeoutSeconds: 900,\n    labels: { app: 'text-to-sql' },\n  });\n  const opts = { region: sb.region };\n  try {\n    await sandscale.sandboxes.writeFile(sb.id, '/workspace/db.sqlite', await readFile(sqlitePath), opts);\n    await sandscale.sandboxes.writeFile(sb.id, '/workspace/run.py', RUNNER, opts);\n    const schema = await sandscale.sandboxes.run(\n      sb.id,\n      ['python3', '-c', \"import sqlite3;c=sqlite3.connect('/workspace/db.sqlite');print('\\\\n'.join(r[0] for r in c.execute(\\\"select sql from sqlite_master where sql is not null\\\")))\"],\n      { ...opts, timeoutSeconds: 30 },\n    );\n\n    const result = await generateText({\n      model: openai('gpt-4.1'),\n      system:\n        'Answer questions about a SQLite database by writing SQL. Use only SELECT statements. ' +\n        'Results are capped at 200 rows; aggregate in SQL instead of reading raw rows. ' +\n        'In your answer, include the final SQL you used.\\n\\nSchema:\\n' + schema.stdout,\n      prompt: question,\n      tools: {\n        run_sql: tool({\n          description: 'Run one read-only SQL query against the database. Returns columns and up to 200 rows as JSON.',\n          inputSchema: z.object({ sql: z.string().max(10_000) }),\n          execute: async ({ sql }) => {\n            await sandscale.sandboxes.writeFile(sb.id, '/workspace/query.sql', sql, opts);\n            const r = await sandscale.sandboxes.run(sb.id, ['python3', '/workspace/run.py'], {\n              ...opts,\n              timeoutSeconds: 60,\n            });\n            if (r.timedOut) return { error: 'query timed out; narrow it or add a WHERE clause' };\n            if (r.exitCode !== 0) return { error: r.stderr.slice(-2_000) };\n            return JSON.parse(r.stdout);\n          },\n        }),\n      },\n      stopWhen: isStepCount(12),\n    });\n    return result.text;\n  } finally {\n    await sandscale.sandboxes.stop(sb.id, opts);\n  }\n}\n```\n\n**A copy, not a connection.** The model's SQL never reaches your production database, so no query can lock a table or slow your app, and no write can land there.\n\n**Read-only at three levels.** The runner opens the file with SQLite's `mode=ro` URI parameter and sets `PRAGMA query_only = ON`. Either alone rejects writes. And the copy is disposable: if both failed, the damage would be confined to a file that is deleted when the sandbox stops.\n\n**A box with no network.** The sandbox is created without a `network` option, and the SDK's default is `none`. Even if the model persuaded the runner to do something unexpected, there is nowhere to send the data.\n\n**Time and row caps.** Each query runs with a time limit (60, in seconds); a timed-out query returns an error the model can act on (\"narrow it\"). Results are capped at 200 rows, and the system prompt tells the model to aggregate in SQL. That keeps context small and nudges the model toward the right kind of query.\n\n**Errors go back to the model.** SQLite's error message, such as a missing column, is returned as the tool result. The model fixes its query on the next step, which is most of what makes text-to-SQL work in practice.\n\n**The schema up front.** The schema is read once, inside the sandbox, and put in the system prompt, so the model does not spend steps discovering tables.\n\nThe sandbox protects your database from the model. It does not decide what the model may know. Every row a query returns goes into the conversation. So:\n\nFor exports too large to upload with one `writeFile` call (the API refuses oversized files with `file_too_large`), prepare a [snapshot](https://sandscale.dev/blog/how-to-start-sandboxes-from-a-prepared-snapshot) that already contains the extract, so each question starts with the data in place. For engines other than SQLite, such as DuckDB over Parquet files, the pattern is the same: a template with the engine installed, files in `/workspace`, and a runner that opens them read-only.\n\nA question that takes a few queries runs for a short time and stops its box. Awake vCPU-hours come from your plan: 100 a month on Free, 1,500 on Pro, 2,000 per member pooled on Team.\n\n*Originally published on the [Sandscale blog](https://sandscale.dev/blog/use-case-text-to-sql-agent-on-a-sandboxed-copy).*", "url": "https://wpnews.pro/news/use-case-a-text-to-sql-agent-that-queries-a-read-only-copy-in-a-sandbox", "canonical_source": "https://dev.to/sandscale/use-case-a-text-to-sql-agent-that-queries-a-read-only-copy-in-a-sandbox-1i5b", "published_at": "2026-11-27 05:35:35+00:00", "updated_at": "2026-11-27 05:47:16.057574+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools"], "entities": ["Sandscale", "Vercel", "OpenAI", "SQLite", "gpt-4.1", "Vercel AI SDK"], "also_reported_by": [], "takeaway": "Run model-generated SQL against a disposable copy in a sandbox opened with SQLite's mode=ro plus PRAGMA query_only, cap results at 200 rows with a truncated flag, and return errors to the tool loop instead of the production database.", "recommendation": {"advice": "Give text-to-SQL agents a sandboxed read-only copy of the data, enforce read-only at both the connection URI and PRAGMA level, and cap returned rows so the model aggregates in SQL.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/use-case-a-text-to-sql-agent-that-queries-a-read-only-copy-in-a-sandbox", "markdown": "https://wpnews.pro/news/use-case-a-text-to-sql-agent-that-queries-a-read-only-copy-in-a-sandbox.md", "text": "https://wpnews.pro/news/use-case-a-text-to-sql-agent-that-queries-a-read-only-copy-in-a-sandbox.txt", "jsonld": "https://wpnews.pro/news/use-case-a-text-to-sql-agent-that-queries-a-read-only-copy-in-a-sandbox.jsonld"}}