### Build SDK from Source
Source: https://querypanel.io/docs
Commands to install dependencies and build the SDK from the monorepo.
```bash
cd node-sdk
bun install
bun run build
```
--------------------------------
### Install QueryPanel SDK
Source: https://querypanel.io/docs
Install the package using your preferred package manager.
```bash
npm install @querypanel/react-sdk
# or
pnpm add @querypanel/react-sdk
# or
yarn add @querypanel/react-sdk
```
--------------------------------
### Install QueryPanel Node SDK
Source: https://querypanel.io/docs
Use npm or bun to install the package in your project.
```bash
npm install @querypanel/node-sdk
# or
bun add @querypanel/node-sdk
```
--------------------------------
### Synchronize database schema with QueryPanel
Source: https://querypanel.io/docs
Use syncSchema to upload table and column metadata. Run this during setup or after schema changes, not on every request.
```typescript
import { QueryPanelSdkAPI } from "@querypanel/node-sdk";
const qp = new QueryPanelSdkAPI(
process.env.QUERYPANEL_URL!,
process.env.PRIVATE_KEY!,
process.env.QUERYPANEL_WORKSPACE_ID!,
);
qp.attachPostgres("pg_demo", createPostgresClient(), {
database: "pg_demo",
tenantFieldName: "tenant_id",
enforceTenantIsolation: true,
allowedTables: ["orders"],
});
qp.attachClickhouse("analytics", (params) => clickhouse.query(params), {
database: "analytics",
tenantFieldName: "customer_id",
tenantFieldType: "String",
});
await qp.syncSchema("pg_demo", { tenantId: "tenant_123" });
await qp.syncSchema("analytics", { tenantId: "tenant_123" });
```
--------------------------------
### Initialize SDK in Deno
Source: https://querypanel.io/docs
Configuration for using the QueryPanel SDK within a Deno environment like Supabase Edge.
```javascript
import { QueryPanelSdkAPI } from "https://esm.sh/@querypanel/node-sdk";
const qp = new QueryPanelSdkAPI(
Deno.env.get("QUERYPANEL_URL")!,
Deno.env.get("PRIVATE_KEY")!,
Deno.env.get("QUERYPANEL_WORKSPACE_ID")!,
);
const response = await qp.ask("Show top products", { tenantId: "tenant_123" });
```
--------------------------------
### Initialize and Use QueryPanel SDK
Source: https://querypanel.io/docs
Configure the SDK with credentials, attach databases, and execute natural language queries.
```typescript
import { QueryPanelSdkAPI } from "@querypanel/node-sdk";
import { Pool } from "pg";
const qp = new QueryPanelSdkAPI(
process.env.QUERYPANEL_URL!,
process.env.PRIVATE_KEY!,
process.env.QUERYPANEL_WORKSPACE_ID!,
{ defaultTenantId: process.env.DEFAULT_TENANT_ID },
);
const pool = new Pool({ connectionString: process.env.POSTGRES_URL });
const createPostgresClient = () => async (sql: string, params?: unknown[]) => {
const client = await pool.connect();
try {
const result = await client.query(sql, params);
return {
rows: result.rows,
fields: result.fields.map((field) => ({ name: field.name })),
};
} finally {
client.release();
}
};
qp.attachPostgres(
"pg_demo",
createPostgresClient(),
{
database: "pg_demo",
description: "PostgreSQL demo database",
tenantFieldName: "tenant_id",
enforceTenantIsolation: true,
allowedTables: ["orders"],
},
);
qp.attachClickhouse(
"analytics",
(params) => clickhouse.query(params),
{
database: "analytics",
tenantFieldName: "customer_id",
tenantFieldType: "String",
},
);
const response = await qp.ask("Top countries by revenue", {
tenantId: "tenant_123",
database: "analytics",
});
console.log(response.sql);
console.log(response.params);
console.table(response.rows);
console.log(response.chart.vegaLiteSpec);
```
--------------------------------
### qp.ask(prompt, options)
Source: https://querypanel.io/docs
Executes a natural language query against a specified database to retrieve SQL, parameters, and visualization specifications.
```APIDOC
## qp.ask(prompt, options)
### Description
Sends a natural language prompt to the QueryPanel engine to generate SQL and visualization specs based on the provided database context.
### Parameters
- **prompt** (string) - Required - The natural language question.
- **options** (object) - Required - Contains `tenantId` and `database`.
```
--------------------------------
### Configure per-client system prompts
Source: https://querypanel.io/docs
Inject custom instructions into the SQL generator to enforce business rules like retention windows or excluded data types.
```typescript
function systemPromptForClient(client: {
retentionDays: number;
}) {
return [
`Data retention: only query rows from the last ${client.retentionDays} days.`,
`Never return a date range longer than ${client.retentionDays} days, even if the user asks for all time or a wider window.`,
"Clamp any requested range to that maximum and bind start/end dates as parameters.",
].join(" ");
}
const client = await loadClient(req); // your auth + billing/retention settings
const response = await qp.ask("Revenue by product over all time", {
tenantId: client.tenantId,
database: "analytics",
systemPrompt: systemPromptForClient(client),
});
```
```typescript
const response = await qp.ask("Show order volume by week", {
tenantId: client.tenantId,
database: "analytics",
systemPrompt: [
"Default time range: last 90 days unless the user names a shorter window.",
"Maximum lookback: 90 days from today.",
"Exclude orders with status refunded or cancelled.",
].join(" "),
});
```
--------------------------------
### qp.createChart(chartData, options)
Source: https://querypanel.io/docs
Saves a chart definition including SQL, parameters, and Vega-Lite specifications.
```APIDOC
## qp.createChart(chartData, options)
### Description
Persists a chart definition to the QueryPanel system for future retrieval and rendering.
### Parameters
- **chartData** (object) - Required - Includes `title`, `prompt`, `sql`, `sql_params`, `vega_lite_spec`, `query_id`, and `target_db`.
- **options** (object) - Required - Includes `tenantId` and `userId`.
```
--------------------------------
### Create a custom theme
Source: https://querypanel.io/docs
Use createTheme to define custom colors, border radius, and typography for the SDK components.
```typescript
import { getColorsByPreset, createTheme } from "@querypanel/react-sdk/themes";
const customTheme = createTheme({
colors: { primary: "#FF6B6B", secondary: "#4ECDC4" },
borderRadius: "1rem",
fontFamily: "Inter, sans-serif",
});
```
--------------------------------
### QueryPanelSdkAPI Constructor
Source: https://querypanel.io/docs
Initializes the QueryPanel SDK instance with configuration options including supported chart types.
```APIDOC
## QueryPanelSdkAPI Constructor
### Description
Initializes a new instance of the QueryPanel SDK.
### Parameters
- **url** (string) - Required - The API base URL.
- **privateKey** (string) - Required - The authentication private key.
- **workspaceId** (string) - Required - The target workspace identifier.
- **options** (object) - Optional - Configuration options including `supportedChartTypes` (ChartType[]).
```
--------------------------------
### QueryPanelSdkAPI.ask
Source: https://querypanel.io/docs
Executes a natural language query against a specified database and returns the generated SQL, parameters, result rows, and a Vega-Lite chart specification.
```APIDOC
## ask(query: string, options: { tenantId: string, database: string })
### Description
Sends a natural language query to the QueryPanel API to retrieve data or insights from an attached database.
### Parameters
- **query** (string) - Required - The natural language question to ask.
- **options** (object) - Required - Configuration object containing:
- **tenantId** (string) - Required - The identifier for the tenant context.
- **database** (string) - Required - The name of the attached database to query.
### Response
- **sql** (string) - The generated SQL query.
- **params** (array) - Parameters used in the SQL query.
- **rows** (array) - The result set from the database.
- **chart** (object) - Contains the `vegaLiteSpec` for visualization.
```
--------------------------------
### QueryPanelSdkAPI.attachPostgres
Source: https://querypanel.io/docs
Registers a PostgreSQL database with the SDK, enabling tenant isolation and schema-aware natural language querying.
```APIDOC
## attachPostgres(name: string, client: Function, options: object)
### Description
Attaches a PostgreSQL database instance to the QueryPanel SDK for query processing.
### Parameters
- **name** (string) - Required - Unique identifier for the database.
- **client** (Function) - Required - A function that executes SQL queries against the database.
- **options** (object) - Required - Configuration including `database`, `description`, `tenantFieldName`, `enforceTenantIsolation`, and `allowedTables`.
```
--------------------------------
### Save and Manage Charts
Source: https://querypanel.io/docs
Create a new chart definition from a natural language query response and list existing charts for a tenant.
```javascript
const response = await qp.ask("Show revenue by country", {
tenantId: "tenant_123",
database: "analytics",
});
if (response.chart.vegaLiteSpec) {
const savedChart = await qp.createChart(
{
title: "Revenue by Country",
prompt: "Show revenue by country",
sql: response.sql,
sql_params: response.params,
vega_lite_spec: response.chart.vegaLiteSpec,
query_id: response.queryId,
target_db: response.target_db,
},
{ tenantId: "tenant_123", userId: "user_456" },
);
}
const charts = await qp.listCharts({ tenantId: "tenant_123" });
```
--------------------------------
### Manage Active Charts and Dashboards
Source: https://querypanel.io/docs
Methods for creating, listing, and bulk-fetching active chart configurations.
```javascript
const activeChart = await qp.createActiveChart(
{
chart_id: "saved_chart_id_from_history",
order: 1,
meta: { width: "full", variant: "dark" },
},
{ tenantId: "tenant_123" },
);
const dashboard = await qp.listActiveCharts({
tenantId: "tenant_123",
withData: true,
});
const all = await qp.listAllActiveCharts({
tenantId: "tenant_123",
withData: true,
});
const { data, missingIds } = await qp.getActiveChartsByIds(
["550e8400-e29b-41d4-a716-446655440000"],
{ tenantId: "tenant_123", withData: true },
);
```
--------------------------------
### qp.listAllCharts(options)
Source: https://querypanel.io/docs
Retrieves a paginated list of all saved charts.
```APIDOC
## qp.listAllCharts(options)
### Description
Fetches all charts associated with a tenant, supporting pagination and optional data inclusion.
### Parameters
- **options** (object) - Required - Includes `tenantId`, `pagination` (page, limit), and `includeData`.
```
--------------------------------
### Configure QueryPanelProvider
Source: https://querypanel.io/docs
Wrap your application with QueryPanelProvider to manage API endpoints and state, then consume data via the useQueryPanel hook.
```typescript
import {
QueryPanelProvider,
QueryInput,
QueryResult,
LoadingState,
EmptyState,
ErrorState,
useQueryPanel,
} from "@querypanel/react-sdk";
function App() {
return (
);
}
function Dashboard() {
const { query, result, isLoading, error, ask, modify, colorPreset } = useQueryPanel();
// ... QueryInput, QueryResult, state components
}
```
--------------------------------
### Use Composable UI Components
Source: https://querypanel.io/docs
Import individual components like VegaChart and DataTable for custom layouts, applying themes via getColorsByPreset.
```typescript
import { VegaChart, DataTable, ChartControls } from "@querypanel/react-sdk";
import { getColorsByPreset } from "@querypanel/react-sdk/themes";
const colors = getColorsByPreset("ocean");
//
```
--------------------------------
### ask
Source: https://querypanel.io/docs
Executes a natural language query.
```APIDOC
## ask(query, options)
### Description
Sends a natural language query to the QueryPanel engine.
### Parameters
- **query** (string) - Required - The natural language prompt.
- **options** (object) - Required - Contains tenantId and optional maxRetry for SQL repair.
```
--------------------------------
### ask
Source: https://querypanel.io/docs
Executes a natural language query against the database, optionally supporting context-aware follow-ups.
```APIDOC
## ask
### Description
Sends a query to the QueryPanel API. Can be used for initial queries or follow-up queries by providing a `querypanelSessionId`.
### Parameters
- **query** (string) - Required - The natural language query string.
- **options** (object) - Required - Includes `tenantId` (string), `database` (string), `supportedChartTypes` (ChartType[], optional), and `querypanelSessionId` (string, optional).
```
--------------------------------
### createActiveChart
Source: https://querypanel.io/docs
Creates a new active chart entry for a specific tenant.
```APIDOC
## createActiveChart(data, options)
### Description
Creates a new active chart record associated with a specific tenant.
### Parameters
- **data** (object) - Required - Contains chart_id, order, and meta configuration.
- **options** (object) - Required - Contains tenantId.
```
--------------------------------
### listSessions
Source: https://querypanel.io/docs
Retrieves a paginated list of sessions for a specific tenant.
```APIDOC
## listSessions
### Description
Lists sessions associated with a tenant, supporting pagination and sorting.
### Parameters
- **options** (object) - Required - Includes `tenantId` (string), `pagination` (object: {page: number, limit: number}), and `sortBy` (string).
```
--------------------------------
### listActiveCharts
Source: https://querypanel.io/docs
Retrieves a list of active charts for a tenant.
```APIDOC
## listActiveCharts(options)
### Description
Fetches active charts for the specified tenant.
### Parameters
- **options** (object) - Required - Contains tenantId and withData boolean flag.
```
--------------------------------
### Execute SQL with Automatic Retry
Source: https://querypanel.io/docs
Configuring query execution with retry logic for handling transient errors.
```javascript
const response = await qp.ask("Show revenue by country", {
tenantId: "tenant_123",
maxRetry: 3,
});
console.log(`Query succeeded after ${response.attempts} attempt(s)`);
```
--------------------------------
### List and Bulk Fetch Charts
Source: https://querypanel.io/docs
Retrieve paginated lists of charts or fetch specific charts by their IDs.
```javascript
const { data, pagination } = await qp.listAllCharts({
tenantId: "tenant_123",
pagination: { page: 1, limit: 50 },
includeData: true,
});
const { data: bulk, missingIds } = await qp.getChartsByIds(
["550e8400-e29b-41d4-a716-446655440000"],
{ tenantId: "tenant_123", includeData: true },
);
```
--------------------------------
### getSession
Source: https://querypanel.io/docs
Retrieves details for a specific session.
```APIDOC
## getSession
### Description
Fetches a single session by its ID.
### Parameters
- **sessionId** (string) - Required - The ID of the session to retrieve.
- **options** (object) - Required - Includes `tenantId` (string) and `includeTurns` (boolean, optional).
```
--------------------------------
### Implement Server-Side JWT Generation and Client-Side Dashboard Embedding
Source: https://querypanel.io/docs
Generate a tenant-scoped JWT on the server using the Node SDK and pass it to the QuerypanelEmbedded component in a React application.
```javascript
// Your API route (Node) — e.g. matches /demo/embed “Run embed” flow
import { QueryPanelSdkAPI } from "@querypanel/node-sdk";
const qp = new QueryPanelSdkAPI(apiBaseUrl, privateKeyPem, organizationId);
const jwt = await qp.createJwt({
tenantId: "tenant_abc",
userId: "user_123",
scopes: ["dashboards:read", "charts:read"],
});
// In your customer-facing React app:
import { QuerypanelEmbedded } from "@querypanel/react-sdk";
export function CustomerAnalytics() {
return (
);
}
```
--------------------------------
### listAllActiveCharts
Source: https://querypanel.io/docs
Retrieves all active charts for a tenant without pagination.
```APIDOC
## listAllActiveCharts(options)
### Description
Calls GET /active-charts/all to retrieve every active chart for a tenant.
### Parameters
- **options** (object) - Required - Contains tenantId and withData boolean flag.
```
--------------------------------
### Custom SQL and Saved Chart Modification
Source: https://querypanel.io/docs
Apply custom SQL overrides or modify existing saved charts by retrieving them first.
```javascript
const customized = await qp.modifyChart(
{
sql: response.sql,
question: "revenue by country",
database: "analytics",
sqlModifications: {
customSql: `SELECT country, SUM(revenue) as total_revenue
FROM orders WHERE status = 'completed' GROUP BY country`,
},
},
{ tenantId: "tenant_123" },
);
const savedChart = await qp.getChart("chart_id_123", { tenantId: "tenant_123" });
const fromSaved = await qp.modifyChart(
{
sql: savedChart.sql,
question: savedChart.prompt ?? "original question",
database: savedChart.target_db ?? "analytics",
params: savedChart.sql_params as Record,
vizModifications: { chartType: "line" },
},
{ tenantId: "tenant_123" },
);
```
--------------------------------
### updateSession
Source: https://querypanel.io/docs
Updates the metadata of an existing session.
```APIDOC
## updateSession
### Description
Updates session properties such as the title.
### Parameters
- **sessionId** (string) - Required - The ID of the session to update.
- **data** (object) - Required - The fields to update (e.g., `title`).
- **options** (object) - Required - Includes `tenantId` (string).
```
--------------------------------
### qp.modifyChart(modifications, options)
Source: https://querypanel.io/docs
Edits SQL or visualization settings for a chart and re-executes the query.
```APIDOC
## qp.modifyChart(modifications, options)
### Description
Modifies an existing chart or query result by applying SQL or visualization changes and regenerating the output.
### Parameters
- **modifications** (object) - Required - Includes `sql`, `question`, `database`, and optional `vizModifications` or `sqlModifications`.
- **options** (object) - Required - Includes `tenantId` and optional `querypanelSessionId`.
```
--------------------------------
### Manage session history and metadata
Source: https://querypanel.io/docs
Perform CRUD operations on sessions including listing, retrieving, updating, and deleting.
```typescript
const sessions = await qp.listSessions({
tenantId: "tenant_123",
pagination: { page: 1, limit: 20 },
sortBy: "updated_at",
});
const session = await qp.getSession("session_abc123", {
tenantId: "tenant_123",
includeTurns: true,
});
await qp.updateSession(
"session_abc123",
{ title: "Q4 Revenue Analysis" },
{ tenantId: "tenant_123" },
);
await qp.deleteSession("session_abc123", { tenantId: "tenant_123" });
```
--------------------------------
### Maintain session context for follow-up queries
Source: https://querypanel.io/docs
Pass the querypanelSessionId from a previous response to enable context-aware follow-up questions.
```typescript
const first = await qp.ask("Revenue by country", {
tenantId: "tenant_123",
database: "analytics",
});
const followUp = await qp.ask("Now filter that to Europe", {
tenantId: "tenant_123",
database: "analytics",
querypanelSessionId: first.querypanelSessionId,
});
```
--------------------------------
### Modify Chart Time Granularity
Source: https://querypanel.io/docs
Adjust SQL parameters for time-based analysis using sqlModifications.
```javascript
const monthly = await qp.modifyChart(
{
sql: response.sql,
question: "revenue over time",
database: "analytics",
sqlModifications: {
timeGranularity: "month",
dateRange: { from: "2024-01-01", to: "2024-12-31" },
},
},
{ tenantId: "tenant_123", querypanelSessionId: response.querypanelSessionId },
);
```
--------------------------------
### Restrict chart types in QueryPanel SDK
Source: https://querypanel.io/docs
Define allowed chart types during SDK initialization or per-query to ensure UI compatibility.
```typescript
import { QueryPanelSdkAPI, ALL_VIZ_CHART_TYPES, type ChartType } from "@querypanel/node-sdk";
const allowed: ChartType[] = ["line", "bar", "column", "pie"];
const qp = new QueryPanelSdkAPI(url, privateKey, workspaceId, {
supportedChartTypes: allowed,
});
await qp.ask("Revenue by month", {
tenantId: "t1",
database: "analytics",
supportedChartTypes: allowed,
});
```
--------------------------------
### Apply brand colors to VegaChart
Source: https://querypanel.io/docs
Pass a colors object to the VegaChart component to override default styling with brand-specific values.
```jsx
```
--------------------------------
### Modify Chart Visualization
Source: https://querypanel.io/docs
Update the visualization properties of a chart using vizModifications.
```javascript
const modified = await qp.modifyChart(
{
sql: response.sql,
question: "revenue by country",
database: "analytics",
vizModifications: {
chartType: "bar",
xAxis: { field: "country", label: "Country" },
yAxis: { field: "revenue", label: "Total Revenue", aggregate: "sum" },
},
},
{ tenantId: "tenant_123" },
);
```
--------------------------------
### getActiveChartsByIds
Source: https://querypanel.io/docs
Bulk-fetches active charts by their unique identifiers.
```APIDOC
## getActiveChartsByIds(ids, options)
### Description
Fetches specific active charts by providing an array of UUIDs.
### Parameters
- **ids** (array) - Required - List of up to 100 UUIDs.
- **options** (object) - Required - Contains tenantId and withData boolean flag.
```
--------------------------------
### deleteSession
Source: https://querypanel.io/docs
Deletes a specific session.
```APIDOC
## deleteSession
### Description
Removes a session from the system.
### Parameters
- **sessionId** (string) - Required - The ID of the session to delete.
- **options** (object) - Required - Includes `tenantId` (string).
```
--------------------------------
### Define QueryResult interface
Source: https://querypanel.io/docs
The QueryResult interface defines the structure of data returned from query operations, including optional SQL and chart specifications.
```typescript
interface QueryResult {
success: boolean;
sql?: string;
rows?: Array>;
fields?: string[];
chart?: {
vegaLiteSpec?: Record;
};
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.