> ## Documentation Index
> Fetch the complete documentation index at: https://docs.edgespark.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# db — EdgeSpark database

> Query your EdgeSpark D1 database with the runtime db import. Use Drizzle selects, inserts, updates, deletes, relations, and batch operations.

`db` is a [Drizzle ORM](https://orm.drizzle.team) instance connected to your project's D1 database. Import it from `edgespark` inside your server code.

## Select

```typescript server/src/index.ts theme={null}
import { db } from "edgespark";
import { and, desc, eq } from "drizzle-orm";
import { posts } from "@defs";

const rows = await db.select().from(posts);

const [post] = await db
  .select()
  .from(posts)
  .where(eq(posts.id, 1));

const recent = await db
  .select()
  .from(posts)
  .orderBy(desc(posts.createdAt))
  .limit(20);

const mine = await db
  .select()
  .from(posts)
  .where(and(eq(posts.authorId, "user_123"), eq(posts.published, 1)));
```

## Insert

```typescript server/src/index.ts theme={null}
import { db } from "edgespark";
import { auth } from "edgespark/http";
import { posts } from "@defs";

const [post] = await db
  .insert(posts)
  .values({
    title: "Hello",
    content: "World",
    authorId: auth.user.id,
  })
  .returning();
```

## Update and delete

```typescript server/src/index.ts theme={null}
import { db } from "edgespark";
import { eq } from "drizzle-orm";
import { posts } from "@defs";

await db
  .update(posts)
  .set({ title: "New title" })
  .where(eq(posts.id, 1));

await db
  .delete(posts)
  .where(eq(posts.id, 1));
```

## Relational queries

If you define relations in `server/src/defs/db_relations.ts`, you can use Drizzle's relational query helpers:

```typescript server/src/index.ts theme={null}
import { db } from "edgespark";

const items = await db.query.posts.findMany({
  with: {
    author: true,
    comments: true,
  },
});
```

## Batch operations

Execute multiple statements atomically with `db.batch()`:

```typescript server/src/index.ts theme={null}
import { db } from "edgespark";
import { auth } from "edgespark/http";
import { eq } from "drizzle-orm";
import { activityLog, posts } from "@defs";

await db.batch([
  db.update(posts).set({ published: 1 }).where(eq(posts.id, 1)),
  db.insert(activityLog).values({
    action: "publish",
    postId: 1,
    userId: auth.user.id,
  }),
]);
```

<Tip>
  Use `db.batch()` instead of multi-statement transactions. See [platform limits](/reference/limits) for the current batch limit and other database constraints.
</Tip>

## See also

<Columns cols={2}>
  <Card title="Use the database" icon="book" href="/guides/database">
    How to define schema, generate migrations, and query D1 in the current scaffold.
  </Card>

  <Card title="Platform limits" icon="gauge" href="/reference/limits">
    Runtime SQL, batch, and deployment constraints that affect database code.
  </Card>
</Columns>
