Astro DB
이 내용은 아직 번역본이 없습니다.
Astro DB is a fully-managed SQL database designed exclusively for Astro. Develop locally or connect to a hosted database managed on our Astro Studio platform.
Installation
Section titled InstallationAdd Astro DB to a new or existing Astro project (requires astro@4.5
or later) with the @astrojs/db
integration (v0.8.1
or later). Astro includes a built-in astro add
command to automate this setup process for you.
If you prefer, you can install @astrojs/db
manually instead.
Define your database
Section titled Define your databaseAstro DB is a complete solution to configuring, developing and querying your data. A local database is created whenever you run astro dev
, using LibSQL to manage your data without the need for Docker or a network connection.
Installing @astrojs/db
with the astro add
command will create a db/config.ts
file in your project where you will define your databases tables:
Columns
Section titled ColumnsData in Astro DB is stored using SQL tables. Tables structure your data into rows and columns, where columns enforce the type of each row value. Astro DB supports the following column types:
Tables
Section titled TablesTables power Astro’s automatic TypeScript typings for your content. When you define a table, Astro will automatically generate and apply a TypeScript interface to it. The result is full TypeScript support when you query your data, including property autocompletion and type-checking.
To configure an individual database table, import and use the defineTable()
and column
utilities from astro:db
.
This example configures a Comment
table with required text columns for author
and body
and then makes it available to your project through the defineDb()
export.
Table References
Section titled Table ReferencesRelationships between tables are a common pattern in database design. For example, a Blog
table may be closely related to other tables of Comment
, Author
, and Category
.
You can define these relations between tables and save them into your database schema using reference columns. To establish a relationship, you will need:
- An identifier column on the referenced table. This is usually an
id
column with theprimaryKey
property. - A column on the base table to store the referenced
id
. This uses thereferences
property establish a relationship.
This example shows a Comment
table’s authorId
column referencing an Author
table’s id
column.
Seed your database
Section titled Seed your databaseIn development, Astro will use your DB config to generate local types according to your schemas. These will be generated fresh each time the dev server is started, and will allow you to query and work with the shape of your data with type safety and autocompletion.
To seed development data for testing and debugging into your Astro project, create a db/seed.ts
file. Import both the db
object and any configured table from astro:db
. Use the db.insert()
function to provide an array of table row data objects.
The following example defines two rows of development data for a Comment
table:
Your development server will automatically restart your database whenever this file changes, regenerating your types and seeding your development data from seed.ts
.
Query your database
Section titled Query your databaseYou can query your database from any Astro page or endpoint in your project using the provided db
ORM and query builder.
Drizzle ORM
Section titled Drizzle ORMAstro DB includes a built-in Drizzle ORM client. There is no setup or manual configuration required to use the client. The Astro DB db
client is automatically configured to talk to your database (local or remote) when you run Astro. It uses your exact database schema definition for type-safe SQL queries with TypeScript errors when you reference a column or table that doesn’t exist.
Select
Section titled SelectThe following example selects all rows of a Comment
table. This returns the complete array of seeded development data from db/seed.ts
which is then available for use in your page template:
select()
API reference for a complete overview.
Insert
Section titled InsertTo accept user input, such as handling form requests and inserting data into your remote hosted database, configure your Astro project for on-demand rendering and add an SSR adapter for your deployment environment.
This example inserts a row into a Comment
table based on a parsed form POST request:
You can also query your database from an API endpoint. This example deletes a row from a Comment
table by the id
param:
See the Drizzle insert()
API reference for a complete overview.
Filtering
Section titled FilteringTo query for table results by a specific property, use Drizzle options for partial selects. For example, add a .where()
call to your select()
query and pass the comparison you want to make.
The following example queries for all rows in a Comment
table that contain the phrase “Astro DB.” Use the like()
operator to check if a phrase is present within the body
:
Drizzle utilities
Section titled Drizzle utilitiesAll Drizzle utilities for building queries are exposed from the astro:db
module. This includes:
- Filter operators like
eq()
andgt()
- Aggregation helpers like
count()
- The
sql
helper for writing raw SQL queries
Relationships
Section titled RelationshipsYou can query related data from multiple tables using a SQL join. To create a join query, extend your db.select()
statement with a join operator. Each function accepts a table to join with and a condition to match rows between the two tables.
This example uses an innerJoin()
function to join Comment
authors with their related Author
information based on the authorId
column. This returns an array of objects with each Author
and Comment
row as top-level properties:
See the Drizzle join reference for all available join operators and config options.
Batch Transactions
Section titled Batch TransactionsAll remote database queries are made as a network request. You may need to “batch” queries together into a single transaction when making a large number of queries, or to have automatic rollbacks if any query fails.
This example seeds multiple rows in a single request using the db.batch()
method:
See the Drizzle db.batch()
docs for more details.
Astro Studio
Section titled Astro StudioAstro DB can connect to the Astro Studio platform to quickly add a hosted database to your project. You can view, manage and deploy new hosted databases all from the Astro Studio web portal.
There are two ways to create a project in Astro Studio:
- via the Astro Studio CLI using
astro link
- via the Astro Studio web UI
To create a new database in the Astro Studio web UI, click the “create project” button in the header and follow the instructions presented. Astro Studio will walk you through the necessary steps, and at the end of the process you’ll have a hosted database configured for your project.
Pushing table schemas
Section titled Pushing table schemasYour table schema will change overtime as your project grows. You can safely test configuration changes locally and push to your Studio database when you deploy.
When creating a Studio project from the dashboard, you will have the option to create a GitHub CI action. This will automatically migrate schema changes when merging with your repository’s main branch.
You can also push schema changes via the CLI using the astro db push
command:
This command will verify changes can be made without data loss and guide on recommended schema changes to resolve conflicts. If a breaking schema change must be made, add the --force-reset
flag to reset all production data.
Pushing data
Section titled Pushing dataYou may need to push data to your Studio database for seeding or data migrations. You can author a .ts
file with the astro:db
module to write type-safe queries. Then, execute the file against your Studio database using the command astro db execute <file-path> --remote
:
The following Comments can be seeded using the command astro db execute db/seed.ts --remote
:
See the CLI reference for a complete list of commands.
Connect to Astro Studio
Section titled Connect to Astro StudioBy default, Astro will use a local database file whenever you run the dev
or build
commands. Tables are recreated from scratch when each command is run, and development seed data will be inserted.
To connect to your hosted Studio database, you can add the --remote
flag. Use this flag for production deploys to have both readable and writable access to your Studio database. This will allow you to accept and persist user data.
Be careful using --remote
in development. This will connect to a live production database, and all inserts, updates, or deletions will be persisted.
To use a remote connection, you will need an app token to authenticate with Studio. Visit the Studio dashboard for token creation and setup instructions.
When you’re ready to deploy, see our Deploy with a Studio Connection guide.
Building Astro DB integrations
Section titled Building Astro DB integrationsAstro integrations can extend user projects with additional Astro DB tables and seed data.
Use the extendDb()
method in the astro:db:setup
hook to register additional Astro DB config and seed files.
The defineDbIntegration()
helper provides TypeScript support and auto-complete for the astro:db:setup
hook.
Integration config and seed files follow the same format as their user-defined equivalents.
Type safe operations in integrations
Section titled Type safe operations in integrationsWhile working on integrations, you may not be able to benefit from Astro’s generated table types exported from astro:db
.
For full type safety, use the asDrizzleTable()
utility to create a table reference object you can use for database operations.
For example, given an integration setting up the following Pets
database table:
The seed file can import Pets
and use asDrizzleTable()
to insert rows into your table with type checking:
The value returned by asDrizzleTable('Pets', Pets)
is equivalent to import { Pets } from 'astro:db'
, but is available even when Astro’s type generation can’t run.
You can use it in any integration code that needs to query or insert into the database.