updated docs on databases

This commit is contained in:
dswbx
2025-06-13 17:18:29 +02:00
parent 0710b5bf1f
commit 2239333f08
6 changed files with 160 additions and 86 deletions

View File

@@ -44,11 +44,10 @@ export const run: CliCommand = (program) => {
) )
.addOption(new Option("-c, --config <config>", "config file")) .addOption(new Option("-c, --config <config>", "config file"))
.addOption( .addOption(
new Option("--db-url <db>", "database url, can be any valid libsql url").conflicts( new Option("--db-url <db>", "database url, can be any valid sqlite url").conflicts(
"config", "config",
), ),
) )
.addOption(new Option("--db-token <db>", "database token").conflicts("config"))
.addOption( .addOption(
new Option("--server <server>", "server type") new Option("--server <server>", "server type")
.choices(PLATFORMS) .choices(PLATFORMS)
@@ -90,7 +89,6 @@ type RunOptions = {
memory?: boolean; memory?: boolean;
config?: string; config?: string;
dbUrl?: string; dbUrl?: string;
dbToken?: string;
server: Platform; server: Platform;
open?: boolean; open?: boolean;
}; };
@@ -102,9 +100,7 @@ export async function makeAppFromEnv(options: Partial<RunOptions> = {}) {
// first start from arguments if given // first start from arguments if given
if (options.dbUrl) { if (options.dbUrl) {
console.info("Using connection from", c.cyan("--db-url")); console.info("Using connection from", c.cyan("--db-url"));
const connection = options.dbUrl const connection = options.dbUrl ? { url: options.dbUrl } : undefined;
? { url: options.dbUrl, authToken: options.dbToken }
: undefined;
app = await makeApp({ connection, server: { platform: options.server } }); app = await makeApp({ connection, server: { platform: options.server } });
// check configuration file to be present // check configuration file to be present

View File

@@ -27,12 +27,13 @@ To serve the API, you can use the `serveLambda` function of the AWS Lambda adapt
```tsx index.mjs ```tsx index.mjs
import { serveLambda } from "bknd/adapter/aws"; import { serveLambda } from "bknd/adapter/aws";
import { libsql } from "bknd/data";
export const handler = serveLambda({ export const handler = serveLambda({
connection: { connection: libsql({
url: process.env.DB_URL!, url: "libsql://your-database-url.turso.io",
authToken: process.env.DB_AUTH_TOKEN! authToken: "your-auth-token",
} }),
}); });
``` ```
Although the runtime would support database as a file, we don't recommend it. You'd need to also bundle the native dependencies which increases the deployment size and cold start time. Instead, we recommend you to use [LibSQL on Turso](/usage/database#sqlite-using-libsql-on-turso). Although the runtime would support database as a file, we don't recommend it. You'd need to also bundle the native dependencies which increases the deployment size and cold start time. Instead, we recommend you to use [LibSQL on Turso](/usage/database#sqlite-using-libsql-on-turso).

View File

@@ -34,8 +34,7 @@ import { serve } from "bknd/adapter/bun";
// if the configuration is omitted, it uses an in-memory database // if the configuration is omitted, it uses an in-memory database
serve({ serve({
connection: { connection: {
url: process.env.DB_URL!, url: "file:data.db"
authToken: process.env.DB_AUTH_TOKEN!
} }
}); });
``` ```

View File

@@ -18,9 +18,7 @@ docker build -t bknd .
If you want to override the bknd version used, you can pass a `VERSION` build argument: If you want to override the bknd version used, you can pass a `VERSION` build argument:
```bash ```bash
docker build --build-arg VERSION=<version> -t bknd . docker build --build-arg VERSION=<version> -t bknd .
```` ```
```bash
## Running the Docker container ## Running the Docker container
To run the Docker container, run the following command: To run the Docker container, run the following command:
@@ -34,10 +32,6 @@ You can pass the same CLI arguments (see [Using the CLI](https://docs.bknd.io/cl
```bash ```bash
docker run -p 1337:1337 -e ARGS="--db-url file:/data/data.db" bknd docker run -p 1337:1337 -e ARGS="--db-url file:/data/data.db" bknd
``` ```
Or connect to a remote turso database:
```bash
docker run -p 1337:1337 -e ARGS="--db-url libsql://<db>.turso.io --db-token <token>" bknd
```
To mount the data directory to the host, you can use the `-v` flag: To mount the data directory to the host, you can use the `-v` flag:
```bash ```bash

View File

@@ -7,6 +7,12 @@ import { Stackblitz, examples } from "/snippets/stackblitz.mdx"
Glad you're here! **bknd** is a lightweight, infrastructure agnostic and feature-rich backend that runs in any JavaScript environment. Glad you're here! **bknd** is a lightweight, infrastructure agnostic and feature-rich backend that runs in any JavaScript environment.
- Instant backend with full REST API
- Built on Web Standards for maximum compatibility
- Multiple run modes (standalone, runtime, framework)
- Official API and React SDK with type-safety
- React elements for auto-configured authentication and media components
## Preview ## Preview
Here is a preview of **bknd** in StackBlitz: Here is a preview of **bknd** in StackBlitz:
<Stackblitz {...examples.adminRich} /> <Stackblitz {...examples.adminRich} />
@@ -96,12 +102,12 @@ The following databases are currently supported. Request a new integration if yo
<CardGroup cols={2}> <CardGroup cols={2}>
<Card <Card
title="LibSQL/SQLite" title="SQLite"
icon={<div className="text-primary-light">{libsql}</div>} icon={<div className="text-primary-light">{sqlite}</div>}
href="/usage/database#database" href="/usage/database#database"
/> />
<Card <Card
title="Turso" title="Turso/LibSQL"
icon={<div className="text-primary-light">{turso}</div>} icon={<div className="text-primary-light">{turso}</div>}
href="/usage/database#sqlite-using-libsql-on-turso" href="/usage/database#sqlite-using-libsql-on-turso"
/> />

View File

@@ -3,53 +3,132 @@ title: 'Database'
description: 'Choosing the right database configuration' description: 'Choosing the right database configuration'
--- ---
In order to use **bknd**, you need to prepare access information to your database and install the dependencies. Connections to the database are managed using Kysely. Therefore, all [its dialects](https://kysely.dev/docs/dialects) are theoretically supported. In order to use **bknd**, you need to prepare access information to your database and potentially install additional dependencies. Connections to the database are managed using Kysely. Therefore, all [its dialects](https://kysely.dev/docs/dialects) are theoretically supported.
Currently supported and tested databases are:
- SQLite (embedded): Node.js SQLite, Bun SQLite, LibSQL, SQLocal
- SQLite (remote): Turso, Cloudflare D1
- Postgres: Vanilla Postgres, Supabase, Neon, Xata
## Database By default, bknd will try to use a SQLite database in-memory. Depending on your runtime, a different SQLite implementation will be used.
### SQLite in-memory
The easiest to get started is using SQLite in-memory. When serving the API in the "Integrations", ## Defining the connection
the function accepts an object with connection details. To use an in-memory database, you can either omit the object completely or explicitly use it as follows: There are mainly 3 ways to define the connection to your database, when
```json 1. creating an app using `App.create()` or `createApp()`
{ 2. creating an app using a [Framework or Runtime adapter](/integration/introduction)
"url": ":memory:" 3. starting a quick instance using the [CLI](/usage/cli#using-configuration-file-bknd-config)
}
When creating an app using `App.create()` or `createApp()`, you can pass a connection object in the configuration object.
```typescript app.ts
import { createApp } from "bknd";
import { sqlite } from "bknd/adapter/sqlite";
// a connection is required when creating an app like this
const app = createApp({
connection: sqlite({ url: ":memory:" }),
});
``` ```
### SQLite as file When using an adapter, or using the CLI, bknd will automatically try to use a SQLite implementation depending on the runtime:
Just like the in-memory option, using a file is just as easy:
```json
{
"url": "file:<path/to/your/database.db>"
}
```
Please note that using SQLite as a file is only supported in server environments.
### SQLite using LibSQL ```javascript app.js
Turso offers a SQLite-fork called LibSQL that runs a server around your SQLite database. To import { serve } from "bknd/adapter/node";
point **bknd** to a local instance of LibSQL, [install Turso's CLI](https://docs.turso.tech/cli/introduction) and run the following command:
```bash serve({
turso dev // connection is optional, but recommended
connection: { url: "file:data.db" },
});
``` ```
The command will yield a URL. Use it in the connection object: You can also pass a connection instance to the `connection` property to explictly use a specific connection.
```json
{ ```javascript app.js
"url": "http://localhost:8080" import { serve } from "bknd/adapter/node";
} import { sqlite } from "bknd/adapter/sqlite";
serve({
connection: sqlite({ url: "file:data.db" }),
});
``` ```
### SQLite using LibSQL on Turso
If you want to use LibSQL on Turso, [sign up for a free account](https://turso.tech/), create a database and point your If you're using [`bknd.config.*`](/extending/config), you can specify the connection on the exported object.
connection object to your new database:
```json ```typescript bknd.config.ts
{ import type { BkndConfig } from "bknd";
"url": "libsql://your-database-url.turso.io",
"authToken": "your-auth-token" export default {
} connection: { url: "file:data.db" },
} as const satisfies BkndConfig;
``` ```
Throughout the documentation, it is assumed you use `bknd.config.ts` to define your connection.
## SQLite
### Using config object
The `sqlite` adapter is automatically resolved based on the runtime.
| Runtime | Adapter | In-Memory | File | Remote |
| ------- | ------- | --------- | ---- | ------ |
| Node.js | `node:sqlite` | ✅ | ✅ | ❌ |
| Bun | `bun:sqlite` | ✅ | ✅ | ❌ |
| Cloudflare Worker/Browser/Edge | `libsql` | 🟠 | 🟠 | ✅ |
The bundled version of the `libsql` connection only works with remote databases. However, you can pass in a `Client` from `@libsql/client`, see [LibSQL](#libsql) for more details.
```typescript bknd.config.ts
import type { BkndConfig } from "bknd";
// no connection is required, bknd will use a SQLite database in-memory
// this does not work on edge environments!
export default {} as const satisfies BkndConfig;
// or explicitly in-memory
export default {
connection: { url: ":memory:" },
} as const satisfies BkndConfig;
// or explicitly as a file
export default {
connection: { url: "file:<path/to/your/database.db>" },
} as const satisfies BkndConfig;
```
### LibSQL
Turso offers a SQLite-fork called LibSQL that runs a server around your SQLite database. The edge-version of the adapter is included in the bundle (remote only):
```typescript bknd.config.ts
import type { BkndConfig } from "bknd";
import { libsql } from "bknd/data";
export default {
connection: libsql({
url: "libsql://your-database-url.turso.io",
authToken: "your-auth-token",
}),
} as const satisfies BkndConfig;
```
If you wish to use LibSQL as file, in-memory or make use of [Embedded Replicas](https://docs.turso.tech/features/embedded-replicas/introduction), you have to pass in the `Client` from `@libsql/client`:
```typescript bknd.config.ts
import type { BkndConfig } from "bknd";
import { libsql } from "bknd/data";
import { createClient } from "@libsql/client";
export default {
connection: libsql(createClient({
url: "libsql://your-database-url.turso.io",
authToken: "your-auth-token",
})),
} as const satisfies BkndConfig;
```
### Cloudflare D1 ### Cloudflare D1
Using the [Cloudflare Adapter](/integration/cloudflare), you can choose to use a D1 database binding. To do so, you only need to add a D1 database to your `wrangler.toml` and it'll pick up automatically. Using the [Cloudflare Adapter](/integration/cloudflare), you can choose to use a D1 database binding. To do so, you only need to add a D1 database to your `wrangler.toml` and it'll pick up automatically.
@@ -63,7 +142,29 @@ export default serve<Env>({
}); });
``` ```
### PostgreSQL
### SQLocal
To use bknd with `sqlocal` for a offline expierence, you need to install the `@bknd/sqlocal` package. You can do so by running the following command:
```bash
npm install @bknd/sqlocal
```
This package uses `sqlocal` under the hood. Consult the [sqlocal documentation](https://sqlocal.dallashoffman.com/guide/setup) for connection options:
```js
import { createApp } from "bknd";
import { SQLocalConnection } from "@bknd/sqlocal";
const app = createApp({
connection: new SQLocalConnection({
databasePath: ":localStorage:",
verbose: true,
})
});
```
## PostgreSQL
To use bknd with Postgres, you need to install the `@bknd/postgres` package. You can do so by running the following command: To use bknd with Postgres, you need to install the `@bknd/postgres` package. You can do so by running the following command:
```bash ```bash
@@ -72,7 +173,7 @@ npm install @bknd/postgres
You can connect to your Postgres database using `pg` or `postgres` dialects. Additionally, you may also define your custom connection. You can connect to your Postgres database using `pg` or `postgres` dialects. Additionally, you may also define your custom connection.
#### Using `pg` ### Using `pg`
To establish a connection to your database, you can use any connection options available on the [`pg`](https://node-postgres.com/apis/client) package. To establish a connection to your database, you can use any connection options available on the [`pg`](https://node-postgres.com/apis/client) package.
@@ -91,7 +192,7 @@ const config = {
serve(config); serve(config);
``` ```
#### Using `postgres` ### Using `postgres`
To establish a connection to your database, you can use any connection options available on the [`postgres`](https://github.com/porsager/postgres) package. To establish a connection to your database, you can use any connection options available on the [`postgres`](https://github.com/porsager/postgres) package.
@@ -104,7 +205,7 @@ serve({
}); });
``` ```
#### Using custom connection ### Using custom connection
Several Postgres hosting providers offer their own clients to connect to their database, e.g. suitable for serverless environments. Several Postgres hosting providers offer their own clients to connect to their database, e.g. suitable for serverless environments.
@@ -148,31 +249,8 @@ serve({
}); });
``` ```
## Custom Connection
### SQLocal Creating a custom connection is as easy as extending the `Connection` class and passing constructing a Kysely instance.
To use bknd with `sqlocal` for a offline expierence, you need to install the `@bknd/sqlocal` package. You can do so by running the following command:
```bash
npm install @bknd/sqlocal
```
This package uses `sqlocal` under the hood. Consult the [sqlocal documentation](https://sqlocal.dallashoffman.com/guide/setup) for connection options:
```js
import { createApp } from "bknd";
import { SQLocalConnection } from "@bknd/sqlocal";
const app = createApp({
connection: new SQLocalConnection({
databasePath: ":localStorage:",
verbose: true,
})
});
```
### Custom Connection
Any bknd app instantiation accepts as connection either `undefined`, a connection object like
described above, or an class instance that extends from `Connection`:
```ts ```ts
import { createApp } from "bknd"; import { createApp } from "bknd";