iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙄

Using Astro DB outside of Astro

に公開

TL;DR

  • Astro DB is Drizzle LibSQL (SQLite) compatible
  • Internally, it sends SQL to an API
  • Structurally, it is possible to force its use without Astro, but it is undocumented and not recommended

What is Astro DB

Astro DB is a fully managed SQL database provided by Astro. As part of the Astro Studio platform, it can be used as a backend database for websites built with Astro.

https://astro.build/db/

Likely use cases include storing website inquiries and managing master data for content.

Usage instructions can be found in the following documentation:

https://docs.astro.build/en/guides/astro-db/

It can be used with both static SSG and dynamic SSR.

Sample projects are available in the following studio-templates repository:

https://github.com/withastro/studio-templates

Astro DB Architecture

Astro DB extends Drizzle ORM to add a database access interface to sites built with Astro.

A database client is generated during the internal Vite build process based on the schema definition.

The database client is based on libSQL, a forked version of the driver designed to turn SQLite into a database server.

The overview of the service architecture is that when an operation on SQLite occurs from the database client, it communicates the SQL via HTTP to the libSQL endpoint hosted by Astro Studio and receives the results in JSON format.

Trying Out the Astro DB API Directly

Based on the knowledge so far, I thought, "Can Astro DB be used outside of the Astro framework?" and decided to verify this.

First, we can see that the DB host is https://db.services.astro.build.

https://github.com/withastro/astro/blob/973a07ff251f78ea48db840ad8573cd9213f7105/packages/db/src/core/utils.ts#L12-L15

Call the /db/query endpoint with an access token attached. You can obtain the access token from https://studio.astro.build/.

We use drizzle-orm/sqlite-proxy to handle SQLite operations via HTTP requests.

https://github.com/withastro/astro/blob/973a07ff251f78ea48db840ad8573cd9213f7105/packages/db/src/runtime/db-client.ts#L27-L48

Parsing the response JSON yields the results.

https://github.com/withastro/astro/blob/973a07ff251f78ea48db840ad8573cd9213f7105/packages/db/src/runtime/db-client.ts#L50-L60

import {z} from "zod"

const remoteResultSchema = z.object({
  columns: z.array(z.string()),
  columnTypes: z.array(z.string()),
  rows: z.array(z.array(z.unknown())),
  rowsAffected: z.number(),
  lastInsertRowid: z.unknown().optional()
});

With this, you can now generate a database client by calling const db = createAstroDb(c.env.ASTRO_DB_TOKEN).

Now, just integrate this into your application. I created a simple message board site where reading and writing to the DB can be confirmed.

https://you-dont-need-astrodb-with-astrojs.pages.dev/ (Please ignore the URL)

I'll build a web app with Hono, as usual.

npm create hono@latest
npm i drizzle-orm zod 

I defined the DB schema as follows:

import { column, defineDb, defineTable, NOW } from 'astro:db';

export const Board = defineTable({
    columns: {
        id: column.number({primaryKey: true}),
        name: column.text(),
        message: column.text(),
        created_at: column.date({ default: NOW }),
    },
});

export default defineDb({
	tables: {
		Board,
	},
});

Apply it with db push. MY_LINK_ID is the Astro DB database ID, which can be obtained from https://studio.astro.build/.

npx astro db link $MY_LINK_ID
npx astro db push

The DB client can use the Drizzle ORM API as is.

app.get('/', async (c) => {
  const db = createAstroDb(c.env.ASTRO_DB_TOKEN)
  const result = await db.run(
      sql.raw('SELECT id, name, message FROM Board ORDER BY created_at LIMIT 100')
  ) as [number, string, string][]
// ...

I'll also write the logic to INSERT into the DB from the form's POST destination.

app.post('/board', async (c) => {
  const {name, message} = await c.req.parseBody()
  const db = createAstroDb(c.env.ASTRO_DB_TOKEN)
  await db.run(
      sql`INSERT INTO Board (name, message)
          VALUES (${name}, ${message})`
  )
  return c.redirect('/')
})

Entire Source Code

Tips: Running SQL Remotely

When you add --remote, operations are performed on the Astro Studio DB; otherwise, the SQLite file is located under the .astro/ directory.

npx astro db shell --query 'select * from Board' --remote
npx astro db execute db/seed.ts  --remote

Discussion