# Node

@quillsql/node.

Install `@quillsql/node` alongside the driver package for your database (and `redis` if using Redis caching):

```sh
npm install @quillsql/node pg
```

```ts
import { Quill } from "@quillsql/node";

const quill = new Quill({
  privateKey: process.env.QUILL_PRIVATE_KEY,
  databaseConnectionString: process.env.POSTGRES_READ,
  databaseType: "postgresql",
});

// authenticateJWT is your own auth middleware
app.post("/quill", authenticateJWT, async (req, res) => {
  const result = await quill.query({
    tenants: [{ tenantField: "organization_id", tenantIds: [req.user.orgId] }],
    metadata: req.body.metadata,
  });
  res.send(result);
});
```

## Bundled and serverless deployments

If your server is bundled (Next.js, Webpack, esbuild), pass a subpath driver adapter instead of `databaseType`:

```ts
import { Quill } from "@quillsql/node";
import { postgres } from "@quillsql/node/postgres";
import { redisCache } from "@quillsql/node/redis";

const quill = new Quill({
  privateKey: process.env.QUILL_PRIVATE_KEY,
  adapter: postgres(process.env.POSTGRES_READ),
  // Only if you use Redis caching
  cache: redisCache({ host: "localhost", port: "6379" }),
});
```

This is required when the bundle is deployed without `node_modules`, such as a Lambda function built with esbuild or a single-file Docker image. With `databaseType`, the SDK loads the driver from `node_modules` at runtime, so a bundler leaves it out of its output. Every request then fails with `Missing optional dependency "pg"`, even though the driver is installed and the same code works locally. An adapter imports the driver directly, so the bundler includes it. A `cache` given as `{ cacheType: "redis", ... }` loads `redis` the same way, so use `redisCache` in its place.

## Optional Driver Packages

| Engine      | Driver Package           | Subpath Adapter             |
| ----------- | ------------------------ | --------------------------- |
| PostgreSQL  | `pg`                     | `@quillsql/node/postgres`   |
| Redshift    | `pg`                     | `@quillsql/node/redshift`   |
| Snowflake   | `snowflake-sdk`          | `@quillsql/node/snowflake`  |
| BigQuery    | `@google-cloud/bigquery` | `@quillsql/node/bigquery`   |
| MySQL       | `mysql2`                 | `@quillsql/node/mysql`      |
| ClickHouse  | `@clickhouse/client`     | `@quillsql/node/clickhouse` |
| SQL Server  | `mssql`                  | `@quillsql/node/mssql`      |
| Databricks  | `@databricks/sql`        | `@quillsql/node/databricks` |
| Redis Cache | `redis`                  | `@quillsql/node/redis`      |

## new Quill

| Option                     | Default                    |                                                                                                                                                                                       |
| -------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `privateKey`               | required                   | `string`: the private key of your Quill environment                                                                                                                                   |
| `adapter`                  |                            | a subpath driver adapter, such as `postgres(connectionString)`; replaces `databaseType`, `databaseConnectionString` and `databaseConfig`                                              |
| `databaseType`             | required without `adapter` | `"postgresql"`, `"redshift"`, `"snowflake"`, `"bigquery"`, `"mysql"`, `"clickhouse"`, `"mssql"` or `"databricks"`                                                                     |
| `databaseConnectionString` |                            | `string`; used over `databaseConfig`                                                                                                                                                  |
| `databaseConfig`           |                            | the connection as an object, by `databaseType`, below                                                                                                                                 |
| `cache`                    |                            | `{ cacheType: "redis" \| "rediss", host, port, username, password, ttl }`, or `redisCache({ ... })` with the same fields: caches results in Redis for `ttl` seconds, 86400 by default |
| `metadataServerURL`        | `https://api.quill.co`     | `string`                                                                                                                                                                              |

| `databaseType`               | `databaseConfig`                                                                            |
| ---------------------------- | ------------------------------------------------------------------------------------------- |
| `"postgresql"`, `"redshift"` | `{ connectionString, ssl? }`                                                                |
| `"snowflake"`                | `{ account, username, password, database, warehouse }`                                      |
| `"bigquery"`                 | `{ projectId, datasetName, credentials }`                                                   |
| `"mysql"`                    | `{ host, port, user, password, database, ssl? }`                                            |
| `"clickhouse"`               | `{ url, username, password }`                                                               |
| `"mssql"`                    | `{ server, port, user, password, database, options?: { encrypt, trustServerCertificate } }` |
| `"databricks"`               | `{ host, path, token, catalog? }`                                                           |

## query

```ts
quill.query(params: QuillQueryParams): Promise<QuillQueryResult>
```

| Param          | Default  |                                                                                               |
| -------------- | -------- | --------------------------------------------------------------------------------------------- |
| `tenants`      | required | `{ tenantField: string; tenantIds: (string \| number)[] }[]`, or `(string \| number)[]`       |
| `metadata`     | required | `req.body.metadata`                                                                           |
| `flags`        |          | `string[]`, or `{ tenantField: string; flags: string[] }[]`                                   |
| `filters`      |          | `{ filterType, operator, value, field, table }[]`                                             |
| `adminEnabled` | `false`  | `boolean`: allows admin tasks, such as editing dashboards; set it from your own authorization |

| Returns   |                                  |
| --------- | -------------------------------- |
| `status`  | `"success"` or `"error"`         |
| `data`    | `object`                         |
| `queries` | `{ queryResults: object[] }`     |
| `error`   | `string`, with `status: "error"` |

## generateClientToken

```ts
quill.generateClientToken(params): Promise<string>
```

| Param        |                                                              |
| ------------ | ------------------------------------------------------------ |
| `publicKey`  | `string`                                                     |
| `tenants`    | `{ tenantField: string; tenantIds: (string \| number)[] }[]` |
| `flags`      | `string[]`, or `{ tenantField: string; flags: string[] }[]`  |
| `expiration` | `number`: milliseconds since the epoch, in the future        |

## alerts

```ts
quill.alerts(): Promise<QuillQueryResult>
```

Checks every tenant's alerts in the private key's environment.

| Returns       |                                                                                                                                                                                                                     |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`      | `"success"` or `"error"`                                                                                                                                                                                            |
| `data.alerts` | `{ name: string; tenantIds: string[]; report: object }[]`: the alerts whose condition is met now, each with the report it is on as its tenant sees it (what `query` returns for the `report` task, with its `rows`) |
| `data.errors` | `{ name: string; tenantIds: string[]; error: string }[]`: the alerts that could not be checked                                                                                                                      |
| `error`       | `string`, with `status: "error"`                                                                                                                                                                                    |

## cache

```ts
quill.cache(params: QuillCacheParams): Promise<QuillCacheResult>
```

Runs dashboards' reports ahead of time, as each tenant sees them, and saves the results in the `cache` Redis. One run at a time per environment, across every server on that Redis, and none within 6 hours of the last one finishing.

```ts
import cron from "node-cron";
import { Quill } from "@quillsql/node";

const quill = new Quill({
  privateKey: process.env.QUILL_PRIVATE_KEY,
  databaseType: "postgresql",
  databaseConnectionString: process.env.DATABASE_URL,
  cache: {
    cacheType: "rediss",
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT,
    username: process.env.REDIS_USERNAME,
    password: process.env.REDIS_PASSWORD,
  },
});

cron.schedule("0 3 * * *", async () => {
  const result = await quill.cache({
    tenants: [
      { tenantField: "organization_id", tenantIds: ["org_1"] },
      { tenantField: "organization_id", tenantIds: ["org_2"] },
    ],
    dashboards: ["Sales", "Marketing"],
  });
  if (result.status === "failed") return console.error("Could not cache:", result.error);
  if (result.failedDashboards.length) console.error("Not cached:", result.failedDashboards);
});
```

| Param              | Default         |                                                                                                                                                        |
| ------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tenants`          | required        | `{ tenantField: string; tenantIds: (string \| number)[] }[]`, or `(string \| number)[]` on your owner tenant field: each entry is cached as one viewer |
| `dashboards`       | every dashboard | `string[]`: dashboard names                                                                                                                            |
| `maxRowsPerReport` | `100000`        | `number`                                                                                                                                               |
| `parallelQueries`  | `10`            | `number`: reports run at once                                                                                                                          |
| `signal`           |                 | `AbortSignal`: stops the run                                                                                                                           |

| Returns            |                                                                                          |
| ------------------ | ---------------------------------------------------------------------------------------- |
| `status`           | `"complete"` or `"failed"`                                                               |
| `cachedDashboards` | `string[]`, with `status: "complete"`                                                    |
| `failedDashboards` | `string[]`: dashboards with a report that could not be cached, with `status: "complete"` |
| `error`            | `string`, with `status: "failed"`                                                        |

## stream

```ts
quill.stream(params: QuillQueryParams & { signal?: AbortSignal }): Promise<AsyncIterable<QuillStreamEvent>>
```

## close

```ts
quill.close(): Promise<void>
```
