# Database

Define SQL tables in TypeScript and query them from your routes, with typed rows.

Hosts: Node, Docker, Cloudflare, Vercel, Netlify, Deno.

:hero-figure{name="database"}

```ts [src/database.ts]
import { defineDatabase } from 'vite-hub/database'
import {
  integer,
  sqliteTable,
  text,
} from 'drizzle-orm/sqlite-core'

// Your tables, written with Drizzle
export default defineDatabase({
  schema: {
    notes: sqliteTable('notes', {
      id: integer('id').primaryKey(),
      title: text('title').notNull(),
    }),
  },
})
```

:::framework{name="Nuxt"}
```ts [nuxt.config.ts]
export default defineNuxtConfig({
  modules: ['vite-hub/nuxt'],
  vitehub: {
    host: 'node',
    // On Node, tables are saved in local SQLite
    database: true,
  },
})
```
:::
:::framework{name="Nitro"}
```ts [vite.config.ts]
import { nitro } from 'nitro/vite'
import { defineConfig } from 'vite'
import { vitehub } from 'vite-hub'

export default defineConfig({
  plugins: [
    vitehub({
      host: 'node',
      // On Node, tables are saved in local SQLite
      database: true,
    }),
    nitro(),
  ],
})
```
:::
:::framework{name="Vite"}
```ts [vite.config.ts]
import { defineConfig } from 'vite'
import { vitehub } from 'vite-hub'

export default defineConfig({
  plugins: [
    vitehub({
      host: 'node',
      // On Node, tables are saved in local SQLite
      database: true,
    }),
  ],
})
```
:::

```ts [server/api/notes.get.ts]
import { defineEventHandler } from 'h3'
import { useDatabase } from 'vite-hub/database'

// List every note
export default defineEventHandler(() => {
  const { db, schema } = useDatabase('default')
  return db.select().from(schema.notes)
})
```

```ts [server/api/notes.post.ts]
import { defineEventHandler, readValidatedBody } from 'h3'
import * as v from 'valibot'
import { useDatabase } from 'vite-hub/database'

// Add a note and return the new row
export default defineEventHandler(async (event) => {
  const body = await readValidatedBody(event, v.object({ title: v.string() }))
  const { db, schema } = useDatabase('default')

  const [note] = await db
    .insert(schema.notes)
    .values({ title: body.title })
    .returning()
  return note
})
```

```ts [server/api/notes/[id].get.ts]
import { eq } from 'drizzle-orm'
import { defineEventHandler, getRouterParam } from 'h3'
import { useDatabase } from 'vite-hub/database'

// Read one note by its id
export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'))
  const { db, schema } = useDatabase('default')

  const [note] = await db
    .select()
    .from(schema.notes)
    .where(eq(schema.notes.id, id))
  return note ?? null
})
```

### [Tables in one file](https://vitehub.dev/docs/database/configure#define-a-database)

Write your tables with Drizzle in `src/database.ts`. ViteHub finds the file and makes migrations.

### [Query from any route](https://vitehub.dev/docs/database/server-api#use-it-at-runtime)

`useDatabase()` gives you a Drizzle client and your tables, with typed results.

### [More than one database](https://vitehub.dev/docs/database/server-api#use-named-databases)

Name a database to keep its data apart, with its own client and connection.

### [Local first, hosted later](https://vitehub.dev/docs/database/hosts#providers)

Use a local SQLite file while you develop. Move to Turso or Cloudflare D1 with the same routes.

### [SQLite or Postgres](https://vitehub.dev/docs/database/configure#define-a-postgres-database)

Use Postgres with postgres.js or node-postgres. `db.$replica` reads from read replicas.

### [Seed, query, and reset](https://vitehub.dev/docs/database/configure#seed-data)

`vitehub seed` adds starting rows, `vitehub database sql` runs a query, and `drop` or `reset` empties the database.

Use Database for relational data with Drizzle. Define tables in a Database Definition and query through the generated `useDatabase()` handle.

Import `useDatabase` from `vite-hub/database` and select the discovered database by name. Do not import generated database definitions or provider bindings into application code. Keep migrations and transaction boundaries with the Database owner.

For Postgres, set `dialect: 'postgresql'`. ViteHub connects with postgres.js, or with `pg` when the Definition sets `driver: 'node-postgres'`. Put read replica URLs in `connection.replicas` and read from them with `db.$replica`; writes and reads of your own writes use `db`. On D1, use `readReplication: true` instead.

For starting rows, write `server/databases/<name>/seed.ts` and run `vitehub seed database`. Inspect data with `vitehub database sql "<query>"`. `vitehub database drop` and `vitehub database reset` delete every table; they ask first, and need `--yes` without a terminal. Each command touches only the local database unless you pass `--remote`.

Prove a migration, a typed read, a write, and a restart or remote-host read. Inspect generated schema and provisioning output before deployment.

<!-- vitehub-docs:section-links -->
## In this section

- [Overview](https://vitehub.dev/raw/docs/database.md) (this page)
- [Get started](https://vitehub.dev/raw/docs/database/get-started.md)
- [Configure](https://vitehub.dev/raw/docs/database/configure.md)
- [Server API](https://vitehub.dev/raw/docs/database/server-api.md)
- [Agent capability](https://vitehub.dev/raw/docs/database/agent-capability.md)
- [Hosts](https://vitehub.dev/raw/docs/database/hosts.md)
- [Limits and errors](https://vitehub.dev/raw/docs/database/limits-and-errors.md)

Next: [DATABASE_CHUNK_INVALID_COUNT](https://vitehub.dev/raw/docs/database/diagnostics/database_chunk_invalid_count.md)

All pages: [llms.txt](https://vitehub.dev/llms.txt)
