diff --git a/astro.sidebar.ts b/astro.sidebar.ts index 6fb3c17e19646..8d26a58e115aa 100644 --- a/astro.sidebar.ts +++ b/astro.sidebar.ts @@ -71,7 +71,6 @@ export const sidebar = [ 'guides/content-collections', 'guides/images', 'guides/data-fetching', - 'guides/astro-db', ], }), group('guides.serverRendering', { diff --git a/public/_redirects b/public/_redirects index c9ed6c8034af6..177723e277c10 100644 --- a/public/_redirects +++ b/public/_redirects @@ -69,6 +69,7 @@ /lighthouse/* /en/guides/migrate-to-astro/ /en/guides/debugging /en/guides/troubleshooting/ /en/quick-started /en/installation/ +/:lang/guides/astro-db/ /en/guides/integrations-guide/db/ # Redirect root to English homepage / /en/getting-started/ diff --git a/src/content/docs/en/guides/astro-db.mdx b/src/content/docs/en/guides/astro-db.mdx deleted file mode 100644 index c6f202d53201d..0000000000000 --- a/src/content/docs/en/guides/astro-db.mdx +++ /dev/null @@ -1,795 +0,0 @@ ---- -title: 'Astro DB' -description: Learn how to use Astro DB, a fully-managed SQL database designed exclusively for Astro. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -Astro DB is a fully-managed SQL database designed for the Astro ecosystem. Develop locally in Astro and deploy to any libSQL-compatible database. - -Astro DB is a complete solution to configuring, developing, and querying your data. A local database is created in `.astro/content.db` whenever you run `astro dev` to manage your data without the need for Docker or a network connection. - -## Installation - -Install the [`@astrojs/db` integration](/en/guides/integrations-guide/db/) using the built-in `astro add` command: - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## Define your database - -Installing `@astrojs/db` with the `astro add` command will automatically create a `db/config.ts` file in your project where you will define your database tables: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### Tables - -Data 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. - -Define your tables in your `db/config.ts` file by providing the structure of the data in your existing libSQL database, or the data you will collect in a new database. This will allow Astro to generate a TypeScript interface to query that table from your project. The result is full TypeScript support when you access your data with property autocompletion and type-checking. - -To configure a database table, import and use the `defineTable()` and `column` utilities from `astro:db`. Then, define a name (case-sensitive) for your table and the type of data in each column. - -This example configures a `Comment` table with required text columns for `author` and `body`. Then, makes it available to your project through the `defineDb()` export. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -See the [table configuration reference](/en/guides/integrations-guide/db/#table-configuration-reference) for a complete reference of table options. - -### Columns - -Astro DB supports the following column types: - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // A string of text. - author: column.text(), - // A whole integer value. - likes: column.number(), - // A true or false value. - flagged: column.boolean(), - // Date/time values queried as JavaScript Date objects. - published: column.date(), - // An untyped JSON object. - metadata: column.json(), - } -}); -``` - -See the [table columns reference](/en/guides/integrations-guide/db/#table-configuration-reference) for more details. - -### Table References - -Relationships 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 the `primaryKey` property. -- A column on the base table to **store the referenced `id`**. This uses the `references` property to establish a relationship. - -This example shows a `Comment` table's `authorId` column referencing an `Author` table's `id` column. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## Seed your database for development - -In development, Astro will use your DB config to generate local types according to your schemas. These will be generated fresh from your seed file 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. - -You will not have access to production data during development unless you [connect to a remote database](#connecting-to-remote-databases) during development. This protects your data while allowing you to test and develop with a working database with type-safety. - -To seed development data for testing and debugging into your Astro project, create a `db/seed.ts` file. Import both the `db` object and your tables defined in `astro:db`. `insert` some initial data into each table. This development data should match the form of both your database schema and production data. - -The following example defines two rows of development data for a `Comment` table, and an `Author` table: - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!'}, - ]) -} -``` - -Your development server will automatically restart your database whenever this file changes, regenerating your types and seeding this development data from `seed.ts` fresh each time. - -## Connect a libSQL database for production - -Astro DB can connect to any local libSQL database or to any server that exposes the libSQL remote protocol, whether managed or self-hosted. - -To connect Astro DB to a libSQL database, set the following environment variables obtained from your database provider: - -- `ASTRO_DB_REMOTE_URL`: the connection URL to the location of your local or remote libSQL DB. This may include [URL configuration options](#remote-url-configuration-options) such as sync and encryption as parameters. -- `ASTRO_DB_APP_TOKEN`: the auth token to your libSQL server. This is required for remote databases, and not needed for [local DBs like files or in-memory](#url-scheme-and-host) databases - -Depending on your service, you may have access to a CLI or web UI to retrieve these values. The following section will demonstrate connecting to Turso and setting these values as an example, but you are free to use any provider. - -### Getting started with Turso - -Turso is the company behind [libSQL](https://github.com/tursodatabase/libsql), the open-source fork of SQLite that powers Astro DB. They provide a fully managed libSQL database platform and are fully compatible with Astro. - -The steps below will guide you through the process of installing the Turso CLI, logging in (or signing up), creating a new database, getting the required environmental variables, and pushing the schema to the remote database. - - - -1. Install the [Turso CLI](https://docs.turso.tech/cli/installation). - -2. [Log in or sign up](https://docs.turso.tech/cli/authentication) to Turso. - -3. Create a new database. In this example the database name is `andromeda`. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. Run the `show` command to see information about the newly created database: - - ```sh "andromeda" - turso db show andromeda - ``` - - Copy the `URL` value and set it as the value for `ASTRO_DB_REMOTE_URL`. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. Create a new token to authenticate requests to the database: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - Copy the output of the command and set it as the value for `ASTRO_DB_APP_TOKEN`. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. Push your DB schema and metadata to the new Turso database. - - ```sh - astro db push --remote - ``` - -7. Congratulations, now you have a database connected! Give yourself a break. 👾 - - ```sh - turso relax - ``` - - - -To explore more features of Turso, check out the [Turso docs](https://docs.turso.tech). - -### Connecting to remote databases - -Astro DB allows you to connect to both local and remote databases. By default, Astro uses a local database file for `dev` and `build` commands, recreating tables and inserting development seed data each time. - -To connect to a hosted remote database, use the `--remote` flag. This flag enables both readable and writable access to your remote database, allowing you to [accept and persist user data](#insert) in production environments. - -Configure your build command to use the `--remote` flag: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -You can also use the flag directly in the command line: - -```bash -# Build with a remote connection -astro build --remote - -# Develop with a remote connection -astro dev --remote -``` - -:::caution -Be careful when using `--remote` in development. This connects to your live production database, and all changes (inserts, updates, deletions) will be persisted. -::: - -The `--remote` flag uses the connection to the remote DB both locally during the build and on the server. Ensure you set the necessary environment variables in both your local development environment and your deployment platform. Additionally, you may need to [configure web mode](/en/guides/integrations-guide/db/#mode) for non-Node.js runtimes such as Cloudflare Workers or Deno. - -When deploying your Astro DB project, make sure your deployment platform's build command is set to `npm run build` (or the equivalent for your package manager) to utilize the `--remote` flag configured in your `package.json`. - -### Remote URL configuration options - -The `ASTRO_DB_REMOTE_URL` environment variable configures the location of your database as well as other options like sync and encryption. - -#### URL scheme and host - -libSQL supports both HTTP and WebSockets as the transport protocol for a remote server. It also supports using a local file or an in-memory DB. Those can be configured using the following URL schemes in the connection URL: - -- `memory:` will use an in-memory DB. The host must be empty in this case. -- `file:` will use a local file. The host is the path to the file (`file:path/to/file.db`). -- `libsql:` will use a remote server through the protocol preferred by the library (this might be different across versions). The host is the address of the server (`libsql://your.server.io`). -- `http:` will use a remote server through HTTP. `https:` can be used to enable a secure connection. The host is the same as for `libsql:`. -- `ws:` will use a remote server through WebSockets. `wss:` can be used to enable a secure connection. The host is the same as for `libsql:`. - -Details of the libSQL connection (e.g. encryption key, replication, sync interval) can be configured as query parameters in the remote connection URL. - -For example, to have an encrypted local file work as an embedded replica to a libSQL server, you can set the following environment variables: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -Using a database file is an advanced feature, and care should be taken when deploying to prevent overriding your database and losing your production data. - -Additionally, this method will not work in serverless deployments, as the file system is not persisted in those environments. -::: - -#### `encryptionKey` - -libSQL has native support for encrypted databases. Passing this search parameter will enable encryption using the given key: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -Embedded replicas are a feature of libSQL clients that creates a full synchronized copy of your database on a local file or in memory for ultra-fast reads. Writes are sent to a remote database defined on the `syncUrl` and synchronized with the local copy. - -Use this property to pass a separate connection URL to turn the database into an embedded replica of another database. This should only be used with the schemes `file:` and `memory:`. The parameter must be URL encoded. - -For example, to have an in-memory embedded replica of a database on `libsql://your.server.io`, you can set the connection URL as such: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -Interval between embedded replica synchronizations in seconds. By default it only synchronizes on startup and after writes. - -This property is only used when `syncUrl` is also set. For example, to set an in-memory embedded replica to synchronize every minute set the following environment variable: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## Query your database - -You can query your database from any [Astro page](/en/basics/astro-pages/#astro-pages), [endpoint](/en/guides/endpoints/), or [action](/en/guides/actions/) in your project using the provided `db` ORM and query builder. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB includes a built-in [Drizzle ORM](https://orm.drizzle.team/) client. There is no setup or manual configuration required to use the client. The Astro DB `db` client is automatically configured to communicate with 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 - -The 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: - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comments

- -{ - comments.map(({ author, body }) => ( -
-

Author: {author}

-

{body}

-
- )) -} -``` - -See the [Drizzle `select()` API reference](https://orm.drizzle.team/docs/select) for a complete overview. - -### Insert - -To accept user input, such as handling form requests and inserting data into your remote hosted database, configure your Astro project for [on-demand rendering](/en/guides/on-demand-rendering/) and [add an adapter](/en/guides/on-demand-rendering/#add-an-adapter) for your deployment environment. - -This example inserts a row into a `Comment` table based on a parsed form POST request: - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // Parse form data - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // Insert form data into the Comment table - await db.insert(Comment).values({ author, body }); - } -} - -// Render the new list of comments on each request -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -You can also use [Astro actions](/en/guides/actions/) to insert data into an Astro DB table. The following example inserts a row into a `Comment` table using an action: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // Actions include type safety with Zod, removing the need - // to check if typeof {value} === 'string' in your pages - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // Return the updated comments - return updatedComments; - }, - }), -}; -``` - - - -See the [Drizzle `insert()` API reference](https://orm.drizzle.team/docs/insert) for a complete overview. - - - -### Delete - -You can also query your database from an API endpoint. This example deletes a row from a `Comment` table by the `id` parameter: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -See the [Drizzle `delete()` API reference](https://orm.drizzle.team/docs/delete) for a complete overview. - - - -### Filtering - -To query for table results by a specific property, use [Drizzle options for partial selects](https://orm.drizzle.team/docs/select#partial-select). For example, add [a `.where()` call](https://orm.drizzle.team/docs/select#filtering) 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](https://orm.drizzle.team/docs/operators#like) to check if a phrase is present within the `body`: - - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Drizzle utilities - -All Drizzle utilities for building queries are exposed from the `astro:db` module. This includes: - -- [Filter operators](https://orm.drizzle.team/docs/operators) like `eq()` and `gt()` -- [Aggregation helpers](https://orm.drizzle.team/docs/select#aggregations-helpers) like `count()` -- [The `sql` helper](https://orm.drizzle.team/docs/sql) for writing raw SQL queries - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### Relationships - -You 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: - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comments

- -{ - comments.map(({ Author, Comment }) => ( -
-

Author: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -See the [Drizzle join reference](https://orm.drizzle.team/docs/joins#join-types) for all available join operators and config options. - - - -### Batch Transactions - -All 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: - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // Seed 100 sample comments into your remote database - // with a single network request. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -See the [Drizzle `db.batch()`](https://orm.drizzle.team/docs/batch-api) docs for more details. - - - -## Pushing changes to your database - -You can push changes made during development to your database. - -### Pushing table schemas - -Your table schema may change over time as your project grows. You can safely test configuration changes locally and push to your remote database when you deploy. - -You can push your local schema changes to your remote database via the CLI using the `astro db push --remote` command: - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -This command will verify that your local changes can be made without data loss and, if necessary, suggest how to safely make changes to your schema in order to resolve conflicts. - -#### Pushing breaking schema changes - -:::danger -__This will destroy your database__. Only perform this command if you do not need your production data. -::: - -If you must change your table schema in a way that is incompatible with your existing data hosted on your remote database, you will need to reset your production database. - -To push a table schema update that includes a breaking change, add the `--force-reset` flag to reset all production data: - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### Renaming tables - -It is possible to rename a table after pushing your schema to your remote database. - -If you **do not have any important production data**, then you can [reset your database](#pushing-breaking-schema-changes) using the `--force-reset` flag. This flag will drop all of the tables in the database and create new ones so that it matches your current schema exactly. - -To rename a table while preserving your production data, you must perform a series of non-breaking changes to push your local schema to your remote database safely. - -The following example renames a table from `Comment` to `Feedback`: - - - -1. In your database config file, add the `deprecated: true` property to the table you want to rename: - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. Add a new table schema (matching the existing table's properties exactly) with the new name: - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. [Push to your remote database](#pushing-table-schemas) with `astro db push --remote`. This will add the new table and mark the old as deprecated. -4. Update any of your local project code to use the new table instead of the old table. You might need to migrate data to the new table as well. -5. Once you are confident that the old table is no longer used in your project, you can remove the schema from your `config.ts`: - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. Push to your remote database again with `astro db push --remote`. The old table will be dropped, leaving only the new, renamed table. - - -### Pushing table data - -You may need to push data to your remote 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 remote database using the command `astro db execute --remote`: - -The following Comments can be seeded using the command `astro db execute db/seed.ts --remote`: - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!' }, - ]) -} -``` - - - -See the [CLI reference](/en/guides/integrations-guide/db/#astro-db-cli-reference) for a complete list of commands. - - - -## Building Astro DB integrations - -[Astro integrations](/en/reference/integrations-reference/) 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. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // Other integration hooks... - }, - }); -} -``` - -Integration [config](#define-your-database) and [seed](#seed-your-database-for-development) files follow the same format as their user-defined equivalents. - -### Type safe operations in integrations - -While 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: - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -The seed file can import `Pets` and use `asDrizzleTable()` to insert rows into your table with type checking: - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -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. - - - - -## Migrate from Astro Studio to Turso - - - -1. In the [Studio dashboard](https://studio.astro.build/), navigate to the project you wish to migrate. In the settings tab, use the "Export Database" button to download a dump of your database. -2. Follow the official instructions to [install the Turso CLI](https://docs.turso.tech/cli/installation) and [sign up or log in](https://docs.turso.tech/cli/authentication) to your Turso account. -3. Create a new database on Turso using the `turso db create` command. - ```sh - turso db create [database-name] - ``` -4. Fetch the database URL using the Turso CLI, and use it as the environment variable `ASTRO_DB_REMOTE_URL`. - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. Create a token to access your database, and use it as the environment variable `ASTRO_DB_APP_TOKEN`. - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. Push your DB schema and metadata to the new Turso database. - ```sh - astro db push --remote - ``` -7. Import the database dump from step 1 into your new Turso DB. - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. Once you have confirmed your project connects to the new database, you can safely delete the project from Astro Studio. - - diff --git a/src/content/docs/en/guides/integrations-guide/db.mdx b/src/content/docs/en/guides/integrations-guide/db.mdx index 05a4009b26253..3f4f08a057f2c 100644 --- a/src/content/docs/en/guides/integrations-guide/db.mdx +++ b/src/content/docs/en/guides/integrations-guide/db.mdx @@ -1,393 +1,11 @@ --- -type: integration title: '@astrojs/db' description: Learn how to use the @astrojs/db integration in your Astro project. -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other i18nReady: true --- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -Astro DB is a fully-managed SQL database designed for the Astro ecosystem: develop locally in Astro and deploy to any [libSQL-compatible database](/en/guides/astro-db/). - -With Astro DB you have a powerful, local, type-safe tool to query and model content as a relational database. - -See the [Astro DB guide](/en/guides/astro-db/) for full usage and examples. - -## Installation - -Astro includes an `astro add` command to automate the setup of official integrations. If you prefer, you can [install integrations manually](#manual-installation) instead. - -Run one of the following commands in a new terminal window. - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### Manual Installation - -If you prefer to set things up from scratch yourself, skip `astro add` and follow these instructions to install Astro DB yourself. - -##### 1. Install the integration from npm via a package manager - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. Add the integration to `astro.config.mjs` - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. Configure your database - -Create a `db/config.ts` file at the root of your project. This is a special file that Astro will automatically load and use to configure your database tables. - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## Configuration - -### `mode` - -

- -**Type:** `'node' | 'web'`
-**Default:** `'node'`
- -

- -Configures the driver to use to connect to your database in production. - -By default, Astro DB uses a Node.js-based libSQL driver for production deployments. The `node` driver mode is sufficient for most Astro hosted or self-hosted websites with Node.js runtimes. This allows you to connect to your database over several protocols, including `memory:`, `file:`, `ws:`, `wss:`, `libsql`, `http`, and `https`, as well as allowing for more advanced features such as [embedded replicas](/en/guides/astro-db/#syncurl). - -When deploying to a serverless environment on a non-Node.js runtime, such as Cloudflare Workers or Deno, a web-based libSQL driver is available. When deploying using the `web` mode, you will be able to make web-based connections over `libsql`, `http`, or `https`. - -To use the web libSQL driver mode for non-Node.js environments, set the `mode` property in your adapter's configuration: - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## Table configuration reference - -### `columns` - -

- -**Type:** `ColumnsConfig` -

- -Table columns are configured using the `columns` object: - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -Columns are configured using the `column` utility. `column` supports the following types: - -- **`column.text(...)`** - store either plain or rich text content -- **`column.number(...)`** - store integer and floating point values -- **`column.boolean(...)`** - store true / false values -- **`column.date(...)`** - store `Date` objects, parsed as ISO strings for data storage -- **`column.json(...)`** - store arbitrary JSON blobs, parsed as stringified JSON for data storage - -There are a few shared configuration values across all columns: - -- `primaryKey` - Set a `number` or `text` column as the unique identifier. -- `optional` - Astro DB uses `NOT NULL` for all columns by default. Set `optional` to `true` to allow null values. -- `default` - Set the default value for newly inserted entries. This accepts either a static value or a string of `sql` for generated values like timestamps. -- `unique` - Mark a column as unique. This prevents duplicate values across entries in the table. -- `references` - Reference a related table by column. This establishes a foreign key constraint, meaning each column value must have a matching value in the referenced table. - -A `text` column can optionally define a list of string literals to serve as an enum for generating types. However, **no runtime validation will be performed**. Removing, adding, and changing values should be handled in your project code. - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// Table definition -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// Resulting type definition -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**Type:** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -Table indexes are used to improve lookup speeds on a given column or combination of columns. The `indexes` property accepts an array of configuration objects specifying the columns to index: - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -This will generate a unique index on the `authorId` and `published` columns with the name `Comment_authorId_published_idx`. - -The following configuration options are available for each index: - -- `on` - A single column or array of column names to index. -- `unique` (optional) - Set to `true` to enforce unique values across the indexed columns. -- `name` (optional) - A custom name for the unique index. This will override Astro's generated name based on the table and column names being indexed (e.g. `Comment_authorId_published_idx`). Custom names are global, so ensure index names do not conflict between tables. - -### `foreignKeys` - -

- -**Type:** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys` is an advanced API for relating multiple table columns. If you only need to reference a single column, try using [the column `references` property.](#columns) +:::caution[Removed] +The Astro DB integration was deprecated in v6.4 and has been removed since Astro v7.0. +If you were using this integration in your project, we recommend migrating to a third-party library for database functionality. See the [Astro v7.0 migration guide](/en/guides/upgrade-to/v7/#removed-astrojsdb) for more details and recommendations on how to update your project. ::: - -Foreign keys are used to establish a relationship between two tables. The `foreignKeys` property accepts an array of configuration objects that may relate one or more columns between tables: - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -Each foreign key configuration object accepts the following properties: - -- `columns` - A single column or array of column names to relate to the referenced table. -- `references` - A function that returns a single column or an array of columns from the referenced table. - -## Astro DB CLI reference - -Astro DB includes a set of CLI commands to interact with your local and libSQL-compatible database. - -These commands are called automatically when using a GitHub CI action, and can be called manually using the `astro db` CLI. - -### `astro db push` - -**Flags:** - -- `--db-app-token ` Provide the remote database app token directly instead of `ASTRO_DB_APP_TOKEN`. -- `--dry-run` Print the generated SQL statements without applying them. -- `--force-reset` Reset all production data if a breaking schema change is required. -- `--remote` Push to your remote database instead of the local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Safely push database configuration changes to your project database. This will check for any risk of data loss and guide you on any recommended migration steps. Use `--remote` to apply changes to your remote database. If a breaking schema change must be made, use `--force-reset` to reset all production data. - -### `astro db verify` - -**Flags:** - -- `--db-app-token ` Provide the remote database app token directly instead of `ASTRO_DB_APP_TOKEN`. -- `--json` Print a machine-readable JSON result from `verify`. -- `--remote` Compare against your remote database instead of the local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Compares your local schema against the remote database to check for any differences between your local and remote database configurations. This is automatically run by `astro db push`. - -`verify` will compare your local `db/config.ts` file with the remote database and warn if changes are detected. It will exit with a non-zero code if changes are required or unsafe, making it useful for CI. - -### `astro db execute ` - -**Flags:** - -- `--db-app-token ` Provide the remote database app token directly instead of `ASTRO_DB_APP_TOKEN`. -- `--remote` Run against your libSQL-compatible database. Omit to run against your local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Execute a `.ts` or `.js` file to read or write to your database. This accepts a file path as an argument, and supports usage of the `astro:db` module to write type-safe queries. Use the `--remote` flag to run against your libSQL-compatible database, or omit the flag to run against your local database file. See how to [seed development data](/en/guides/astro-db/#seed-your-database-for-development) for an example file. - -### `astro db shell --query ` - -**Flags:** - -- `--query` Raw SQL query to execute. -- `--remote` Run against your libSQL-compatible database. Omit to run against your local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Execute a raw SQL query against your database. - -The following example selects all rows from a `Comment` table in a remote database: - -```sh -npx astro db shell --query "SELECT * FROM Comment;" --remote -``` - -## Astro DB utility reference - -The following utilities are imported from the `astro:db` module: - -```ts -import { - isDbError, - getDbError -} from "astro:db"; -``` - -### `isDbError()` - -

- -**Type:** `(err: unknown) => boolean`
- -

- -Checks if an error is a libSQL database exception. This may include a foreign key constraint error when using references, or missing fields when inserting data. You can combine `isDbError()` with a try / catch block to handle database errors in your application: - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`Cannot insert comment with id ${id}\n\n${e.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` - -### `getDbError()` - -

- -**Type:** `(err: unknown) => LibsqlError | undefined`
- -

- -Walks through an error's cause chain to find the underlying libSQL database exception. This returns a `LibsqlError` or `undefined` if the error is not from LibSQL. This is useful when another error (e.g. `DrizzleQueryError`) may wrap the database error. - -The following example extracts the database error from a caught exception and returns the error code and message in the response: - -```ts title="src/pages/api/comment/[id].ts" "getDbError" -import { getDbError } from 'astro:db'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - const dbError = getDbError(e); - if (dbError) { - return new Response(`Database error: ${dbError.code}\n\n${dbError.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` diff --git a/src/content/docs/en/guides/upgrade-to/v7.mdx b/src/content/docs/en/guides/upgrade-to/v7.mdx index d4c9be4c68375..5180af7e92489 100644 --- a/src/content/docs/en/guides/upgrade-to/v7.mdx +++ b/src/content/docs/en/guides/upgrade-to/v7.mdx @@ -78,17 +78,13 @@ If you are using Vite-specific plugins, configuration, or APIs, check the [Vite Most Astro users should be able to upgrade without any changes to their project code. This is primarily a breaking change for Astro integrations and plugins that depend on Vite internals. -### Rust Compiler +### Experimental Flags -The Rust-based Astro compiler, previously available as an experimental flag (`experimental.rustCompiler`), is now the default and only compiler in Astro 7. The Rust compiler delivers significantly faster build times compared to the previous Go-based compiler. +Experimental flags allow you to opt in to features while they are in early development. The following experimental flags have been removed in Astro 7.0 and are now stable, or the new default behavior. -##### What should I do? - -No action is required for most projects. The Rust compiler is a drop-in replacement for the Go-based compiler. - -If you had previously opted in to the Rust compiler via the experimental flag, you can now remove it from your configuration: +Remove these experimental flags from your Astro config if you were previously using them: -```js title="astro.config.mjs" del={4-6} +```js del={5} title="astro.config.mjs" import { defineConfig } from 'astro/config'; export default defineConfig({ @@ -98,4 +94,20 @@ export default defineConfig({ }); ``` -If you encounter any issues with the Rust compiler, please report them on [GitHub](https://github.com/withastro/astro/issues). +#### Experimental features now stable: + +- `rustCompiler`: The Rust-based Astro compiler is now the default and only compiler, replacing the previous Go-based compiler. No action is required for most projects. If you encounter any issues, please report them on [GitHub](https://github.com/withastro/astro/issues). + +### Removed: `@astrojs/db` + +The `@astrojs/db` package has been removed in Astro v7.0 and is no longer maintained. + +#### What should I do? + +Remove `@astrojs/db` from your project's dependencies and replace it with one of the following alternatives: + +- **Node.js built-in SQLite**: Node.js now includes a built-in [`node:sqlite`](https://nodejs.org/api/sqlite.html) module (available since Node.js v22.5.0). This is a good option if you are using the Node.js adapter and were using `@astrojs/db` for local SQLite storage. + +- **[Drizzle ORM](https://orm.drizzle.team/)**: If you were using `@astrojs/db` for its Drizzle-based schema and query API, you can use Drizzle directly with any supported database. + +- **Other database libraries**: Use any database library that suits your deployment platform (e.g. [Turso](https://turso.tech/), [PlanetScale](https://planetscale.com/), [Neon](https://neon.tech/)). diff --git a/src/content/docs/en/reference/cli-reference.mdx b/src/content/docs/en/reference/cli-reference.mdx index 9de5573bd64cd..5190bf9ed6f9f 100644 --- a/src/content/docs/en/reference/cli-reference.mdx +++ b/src/content/docs/en/reference/cli-reference.mdx @@ -266,7 +266,6 @@ Running `astro dev`, `astro build` or `astro check` will run the `sync` command Generates TypeScript types for all Astro modules. This sets up a [`.astro/types.d.ts` file](/en/guides/typescript/#setup) for type inferencing, and defines modules for features that rely on generated types: - The `astro:content` module for the [Content Collections API](/en/guides/content-collections/). -- The `astro:db` module for [Astro DB](/en/guides/astro-db/). - The `astro:env` module for [Astro Env](/en/guides/environment-variables/). - The `astro:actions` module for [Astro Actions](/en/guides/actions/) diff --git a/src/content/docs/es/guides/astro-db.mdx b/src/content/docs/es/guides/astro-db.mdx deleted file mode 100644 index 53d32c8ea0eb5..0000000000000 --- a/src/content/docs/es/guides/astro-db.mdx +++ /dev/null @@ -1,792 +0,0 @@ ---- -title: 'Astro DB' -description: Aprende a usar Astro DB, una base de datos SQL completamente gestionada diseñada exclusivamente para Astro. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -Astro DB es una base de datos SQL completamente gestionada diseñada para el ecosistema de Astro. Desarrolla localmente en Astro y despliega en cualquier base de datos compatible con libSQL. - -Astro DB es una solución completa para configurar, desarrollar y consultar tus datos. Una base de datos local se crea en `.astro/content.db` cada vez que ejecutas `astro dev` para gestionar tus datos sin necesidad de Docker o una conexión de red. - -## Instalación - -Instala la integración [`@astrojs/db`](/es/guides/integrations-guide/db/) usando el comando incorporado `astro add`: - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## Define tu base de datos - -Instalar `@astrojs/db` con el comando `astro add` creará automáticamente un archivo `db/config.ts` en tu proyecto donde definirás las tablas de tu base de datos: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### Tablas - -Los datos en Astro DB se almacenan usando tablas SQL. Las tablas estructuran tus datos en filas y columnas, donde las columnas hacen cumplir el tipo de cada valor de fila. - -Define tus tablas en tu archivo `db/config.ts` proporcionando la estructura de los datos en tu base de datos libSQL existente, o los datos que recopilarás en una nueva base de datos. Esto permitirá a Astro generar una interfaz de TypeScript para consultar esa tabla desde tu proyecto. El resultado es soporte completo de TypeScript cuando accedes a tus datos con autocompletado de propiedades y verificación de tipos. - -Para configurar una tabla de base de datos, importa y usa las utilidades `defineTable()` y `column` desde `astro:db`. Luego, define un nombre (sensible a mayúsculas) para tu tabla y el tipo de datos en cada columna. - -Este ejemplo configura una tabla `Comment` con columnas de texto obligatorias para `author` y `body`. Luego, la hace disponible para tu proyecto a través de la exportación `defineDb()`. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -Consulta la [referencia de configuración de tablas](/es/guides/integrations-guide/db/#table-configuration-reference) para una referencia completa de las opciones de tabla. - -### Columnas - -Astro DB admite los siguientes tipos de columna: - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // Una cadena de texto. - author: column.text(), - // Un valor entero completo. - likes: column.number(), - // Un valor verdadero o falso. - flagged: column.boolean(), - // Valores de fecha/hora consultados como objetos Date de JavaScript. - published: column.date(), - // Un objeto JSON sin tipo. - metadata: column.json(), - } -}); -``` - -Consulta la [referencia de columnas de tabla](/es/guides/integrations-guide/db/#table-configuration-reference) para más detalles. - -### Referencias de Tabla - -Las relaciones entre tablas son un patrón común en el diseño de bases de datos. Por ejemplo, una tabla `Blog` puede estar estrechamente relacionada con otras tablas de `Comment`, `Author` y `Category`. - -Puedes definir estas relaciones entre tablas y guardarlas en tu esquema de base de datos usando **columnas de referencia**. Para establecer una relación, necesitarás: - -- Una **columna identificadora** en la tabla referenciada. Suele ser una columna `id` con la propiedad `primaryKey`. -- Una columna en la tabla base para **almacenar el `id` referenciado**. Esto usa la propiedad `references` para establecer una relación. - -Este ejemplo muestra una columna `authorId` de la tabla `Comment` que referencia una columna `id` de la tabla `Author`. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## Sembrar tu base de datos para desarrollo - -En desarrollo, Astro usará tu configuración de DB para generar tipos locales según tus esquemas. Estos se generarán de nuevo desde tu archivo de semilla cada vez que se inicie el servidor de desarrollo, y te permitirán consultar y trabajar con la forma de tus datos con seguridad de tipos y autocompletado. - -No tendrás acceso a datos de producción durante el desarrollo a menos que [te conectes a una base de datos remota](#conectando-a-bases-de-datos-remotas) durante el desarrollo. Esto protege tus datos mientras te permite probar y desarrollar con una base de datos funcional con seguridad de tipos. - -Para sembrar datos de desarrollo para pruebas y depuración en tu proyecto de Astro, crea un archivo `db/seed.ts`. Importa tanto el objeto `db` como tus tablas definidas en `astro:db`. `inserta` algunos datos iniciales en cada tabla. Estos datos de desarrollo deben coincidir con la forma de tu esquema de base de datos y de los datos de producción. - -El siguiente ejemplo define dos filas de datos de desarrollo para una tabla `Comment` y una tabla `Author`: - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: '¡Espero que te guste Astro DB!' }, - { authorId: 2, body: '¡Disfrútalo!'}, - ]) -} -``` - -Tu servidor de desarrollo reiniciará automáticamente tu base de datos cada vez que este archivo cambie, regenerando tus tipos y sembrando estos datos de desarrollo desde `seed.ts` de nuevo cada vez. - -## Conecta una base de datos libSQL para producción - -Astro DB puede conectarse a cualquier base de datos libSQL local o a cualquier servidor que exponga el protocolo remoto de libSQL, ya sea gestionado o autoalojado. - -Para conectar Astro DB a una base de datos libSQL, establece las siguientes variables de entorno obtenidas de tu proveedor de base de datos: - -- `ASTRO_DB_REMOTE_URL`: la URL de conexión a la ubicación de tu base de datos libSQL local o remota. Esto puede incluir [opciones de configuración de URL](#opciones-de-configuración-de-url-remota) como sincronización y cifrado como parámetros. -- `ASTRO_DB_APP_TOKEN`: el token de autenticación para tu servidor libSQL. Esto es obligatorio para bases de datos remotas, y no es necesario para [bases de datos locales como archivos o en memoria](#esquema-de-url-y-host) - -Dependiendo de tu servicio, puedes tener acceso a una CLI o interfaz web para recuperar estos valores. La siguiente sección demostrará conectarse a Turso y establecer estos valores como ejemplo, pero eres libre de usar cualquier proveedor. - -### Comenzando con Turso - -Turso es la empresa detrás de [libSQL](https://github.com/tursodatabase/libsql), el fork de código abierto de SQLite que impulsa Astro DB. Proporcionan una plataforma de base de datos libSQL completamente gestionada y son totalmente compatibles con Astro. - -Los pasos a continuación te guiarán a través del proceso de instalar la CLI de Turso, iniciar sesión (o registrarte), crear una nueva base de datos, obtener las variables de entorno requeridas y empujar el esquema a la base de datos remota. - - - -1. Instala la [CLI de Turso](https://docs.turso.tech/cli/installation). - -2. [Inicia sesión o regístrate](https://docs.turso.tech/cli/authentication) en Turso. - -3. Crea una nueva base de datos. En este ejemplo el nombre de la base de datos es `andromeda`. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. Ejecuta el comando `show` para ver información sobre la base de datos recién creada: - - ```sh "andromeda" - turso db show andromeda - ``` - - Copia el valor `URL` y establécelo como el valor para `ASTRO_DB_REMOTE_URL`. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. Crea un nuevo token para autenticar las solicitudes a la base de datos: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - Copia la salida del comando y establécelo como el valor para `ASTRO_DB_APP_TOKEN`. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. Empuja tu esquema de DB y metadatos a la nueva base de datos de Turso. - - ```sh - astro db push --remote - ``` - -7. ¡Felicidades, ahora tienes una base de datos conectada! Date un descanso. 👾 - - ```sh - turso relax - ``` - - - -Para explorar más características de Turso, consulta la [documentación de Turso](https://docs.turso.tech). - -### Conectando a bases de datos remotas - -Astro DB te permite conectarte tanto a bases de datos locales como remotas. Por defecto, Astro usa un archivo de base de datos local para los comandos `dev` y `build`, recreando tablas e insertando datos de semilla de desarrollo cada vez. - -Para conectarte a una base de datos remota alojada, usa la bandera `--remote`. Esta bandera habilita tanto acceso de lectura como escritura a tu base de datos remota, permitiéndote [aceptar y persistir datos de usuarios](#insertar) en entornos de producción. - -Configura tu comando de construcción para usar la bandera `--remote`: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -También puedes usar la bandera directamente en la línea de comandos: - -```bash -# Construir con una conexión remota -astro build --remote - -# Desarrollar con una conexión remota -astro dev --remote -``` - -:::caution -Ten cuidado al usar `--remote` en desarrollo. Esto se conecta a tu base de datos de producción en vivo, y todos los cambios (inserciones, actualizaciones, eliminaciones) persistirán. -::: - -La bandera `--remote` usa la conexión a la base de datos remota tanto localmente durante la construcción como en el servidor. Asegúrate de establecer las variables de entorno necesarias tanto en tu entorno de desarrollo local como en tu plataforma de despliegue. Además, es posible que necesites [configurar el modo web](/es/guides/integrations-guide/db/#mode) para entornos de ejecución que no sean Node.js, como Cloudflare Workers o Deno. - -Al desplegar tu proyecto de Astro DB, asegúrate de que el comando de construcción de tu plataforma de despliegue esté configurado como `npm run build` (o el equivalente para tu gestor de paquetes) para utilizar la bandera `--remote` configurada en tu `package.json`. - -### Opciones de configuración de URL remota - -La variable de entorno `ASTRO_DB_REMOTE_URL` configura la ubicación de tu base de datos, así como otras opciones como sincronización y cifrado. - -#### Esquema de URL y host - -libSQL admite tanto HTTP como WebSockets como protocolo de transporte para un servidor remoto. También admite usar un archivo local o una base de datos en memoria. Estos se pueden configurar usando los siguientes esquemas de URL en la URL de conexión: - -- `memory:` usará una base de datos en memoria. El host debe estar vacío en este caso. -- `file:` usará un archivo local. El host es la ruta al archivo (`file:path/to/file.db`). -- `libsql:` usará un servidor remoto a través del protocolo preferido por la biblioteca (esto puede variar entre versiones). El host es la dirección del servidor (`libsql://your.server.io`). -- `http:` usará un servidor remoto a través de HTTP. Se puede usar `https:` para habilitar una conexión segura. El host es el mismo que para `libsql:`. -- `ws:` usará un servidor remoto a través de WebSockets. Se puede usar `wss:` para habilitar una conexión segura. El host es el mismo que para `libsql:`. - -Los detalles de la conexión libSQL (por ejemplo, clave de cifrado, replicación, intervalo de sincronización) se pueden configurar como parámetros de consulta en la URL de conexión remota. - -Por ejemplo, para tener un archivo local cifrado que funcione como una réplica embebida de un servidor libSQL, puedes establecer las siguientes variables de entorno: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -Usar un archivo de base de datos es una característica avanzada, y se debe tener cuidado al desplegar para evitar sobrescribir tu base de datos y perder tus datos de producción. - -Además, este método no funcionará en despliegues sin servidor (serverless), ya que el sistema de archivos no persiste en esos entornos. -::: - -#### `encryptionKey` - -libSQL tiene soporte nativo para bases de datos cifradas. Pasar este parámetro de búsqueda habilitará el cifrado usando la clave dada: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -Las réplicas embebidas son una característica de los clientes libSQL que crea una copia completamente sincronizada de tu base de datos en un archivo local o en memoria para lecturas ultrarrápidas. Las escrituras se envían a una base de datos remota definida en `syncUrl` y se sincronizan con la copia local. - -Usa esta propiedad para pasar una URL de conexión separada para convertir la base de datos en una réplica embebida de otra base de datos. Esto solo debe usarse con los esquemas `file:` y `memory:`. El parámetro debe estar codificado en URL. - -Por ejemplo, para tener una réplica embebida en memoria de una base de datos en `libsql://your.server.io`, puedes establecer la URL de conexión así: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -Intervalo entre sincronizaciones de réplicas embebidas en segundos. Por defecto solo se sincroniza al inicio y después de escrituras. - -Esta propiedad solo se usa cuando `syncUrl` también está establecida. Por ejemplo, para establecer una réplica embebida en memoria que se sincronice cada minuto, establece la siguiente variable de entorno: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## Consulta tu base de datos - -Puedes consultar tu base de datos desde cualquier [página de Astro](/es/basics/astro-pages/#páginas-de-astro), [endpoint](/es/guides/endpoints/), o [acción](/es/guides/actions/) en tu proyecto usando el ORM `db` y el constructor de consultas proporcionados. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB incluye un cliente [Drizzle ORM](https://orm.drizzle.team/) incorporado. No se requiere configuración o configuración manual para usar el cliente. El cliente `db` de Astro DB se configura automáticamente para comunicarse con tu base de datos (local o remota) cuando ejecutas Astro. Usa tu definición exacta de esquema de base de datos para consultas SQL con seguridad de tipos con errores de TypeScript cuando haces referencia a una columna o tabla que no existe. - -### Seleccionar - -El siguiente ejemplo selecciona todas las filas de una tabla `Comment`. Esto devuelve el arreglo completo de datos de desarrollo sembrados desde `db/seed.ts` que luego está disponible para usar en tu plantilla de página: - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comentarios

- -{ - comments.map(({ author, body }) => ( -
-

Autor: {author}

-

{body}

-
- )) -} -``` - -Consulta la [referencia de la API `select()` de Drizzle](https://orm.drizzle.team/docs/select) para una descripción completa. - -### Insertar - -Para aceptar entrada de usuario, como manejar solicitudes de formularios e insertar datos en tu base de datos remota alojada, configura tu proyecto de Astro para [renderizado bajo demanda](/es/guides/on-demand-rendering/) y [agrega un adaptador](/es/guides/on-demand-rendering/#agrega-un-adaptador) para tu entorno de despliegue. - -Este ejemplo inserta una fila en una tabla `Comment` basada en una solicitud POST de formulario analizada: - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // Analiza los datos del formulario - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // Inserta los datos del formulario en la tabla Comment - await db.insert(Comment).values({ author, body }); - } -} - -// Renderiza la nueva lista de comentarios en cada solicitud -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -También puedes usar [acciones de Astro](/es/guides/actions/) para insertar datos en una tabla de Astro DB. El siguiente ejemplo inserta una fila en una tabla `Comment` usando una acción: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // Las acciones incluyen seguridad de tipos con Zod, eliminando la necesidad - // de verificar si typeof {valor} === 'string' en tus páginas - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // Devuelve los comentarios actualizados - return updatedComments; - }, - }), -}; -``` - - - -Consulta la [referencia de la API `insert()` de Drizzle](https://orm.drizzle.team/docs/insert) para una descripción completa. - - - -### Eliminar - -También puedes consultar tu base de datos desde un endpoint de API. Este ejemplo elimina una fila de una tabla `Comment` por el parámetro `id`: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -Consulta la [referencia de la API `delete()` de Drizzle](https://orm.drizzle.team/docs/delete) para una descripción completa. - - - -### Filtrado - -Para consultar resultados de tabla por una propiedad específica, usa [opciones de Drizzle para selecciones parciales](https://orm.drizzle.team/docs/select#partial-select). Por ejemplo, agrega [una llamada `.where()`](https://orm.drizzle.team/docs/select#filtering) a tu consulta `select()` y pasa la comparación que quieres hacer. - -El siguiente ejemplo consulta todas las filas en una tabla `Comment` que contengan la frase "Astro DB". Usa [el operador `like()`](https://orm.drizzle.team/docs/operators#like) para verificar si una frase está presente dentro del `body`: - - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Utilidades de Drizzle - -Todas las utilidades de Drizzle para construir consultas están expuestas desde el módulo `astro:db`. Esto incluye: - -- [Operadores de filtro](https://orm.drizzle.team/docs/operators) como `eq()` y `gt()` -- [Ayudantes de agregación](https://orm.drizzle.team/docs/select#aggregations-helpers) como `count()` -- [El ayudante `sql`](https://orm.drizzle.team/docs/sql) para escribir consultas SQL crudas - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### Relaciones - -Puedes consultar datos relacionados desde múltiples tablas usando un join de SQL. Para crear una consulta de join, extiende tu sentencia `db.select()` con un operador de join. Cada función acepta una tabla con la que unir y una condición para emparejar filas entre las dos tablas. - -Este ejemplo usa una función `innerJoin()` para unir autores de `Comment` con su información de `Author` relacionada basada en la columna `authorId`. Esto devuelve un arreglo de objetos con cada fila de `Author` y `Comment` como propiedades de primer nivel: - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comentarios

- -{ - comments.map(({ Author, Comment }) => ( -
-

Autor: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -Consulta la [referencia de join de Drizzle](https://orm.drizzle.team/docs/joins#join-types) para todos los operadores de join y opciones de configuración disponibles. - - - -### Transacciones por Lotes - -Todas las consultas a bases de datos remotas se realizan como una solicitud de red. Es posible que necesites "agrupar" consultas juntas en una sola transacción cuando hagas un gran número de consultas, o para tener reversiones automáticas si falla alguna consulta. - -Este ejemplo siembra múltiples filas en una sola solicitud usando el método `db.batch()`: - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // Siembra 100 comentarios de ejemplo en tu base de datos remota - // con una sola solicitud de red. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Comentario de prueba ${i}` })); - } - await db.batch(queries); -} -``` - - - -Consulta la documentación de [`db.batch()` de Drizzle](https://orm.drizzle.team/docs/batch-api) para más detalles. - - - -## Empujando cambios a tu base de datos - -Puedes empujar cambios realizados durante el desarrollo a tu base de datos. - -### Empujando esquemas de tabla - -Tu esquema de tabla puede cambiar con el tiempo a medida que tu proyecto crece. Puedes probar de manera segura cambios de configuración localmente y empujar a tu base de datos remota cuando despliegues. - -Puedes empujar tus cambios de esquema local a tu base de datos remota a través de la CLI usando el comando `astro db push --remote`: - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -Este comando verificará que tus cambios locales se pueden realizar sin pérdida de datos y, si es necesario, sugerirá cómo hacer cambios en tu esquema de manera segura para resolver conflictos. - -#### Empujando cambios de esquema que rompen compatibilidad - -:::danger -__Esto destruirá tu base de datos__. Solo realiza este comando si no necesitas tus datos de producción. -::: - -Si debes cambiar tu esquema de tabla de una manera que es incompatible con tus datos existentes alojados en tu base de datos remota, necesitarás resetear tu base de datos de producción. - -Para empujar una actualización de esquema de tabla que incluya un cambio que rompe compatibilidad, agrega la bandera `--force-reset` para resetear todos los datos de producción: - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### Renombrando tablas - -Es posible renombrar una tabla después de haber empujado tu esquema a tu base de datos remota. - -Si **no tienes datos de producción importantes**, entonces puedes [resetear tu base de datos](#empujando-cambios-de-esquema-que-rompen-compatibilidad) usando la bandera `--force-reset`. Esta bandera eliminará todas las tablas de la base de datos y creará nuevas para que coincida exactamente con tu esquema actual. - -Para renombrar una tabla mientras preservas tus datos de producción, debes realizar una serie de cambios no destructivos para empujar tu esquema local a tu base de datos remota de manera segura. - -El siguiente ejemplo renombra una tabla de `Comment` a `Feedback`: - - - -1. En tu archivo de configuración de base de datos, agrega la propiedad `deprecated: true` a la tabla que quieres renombrar: - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. Agrega un nuevo esquema de tabla (coincidiendo exactamente con las propiedades de la tabla existente) con el nuevo nombre: - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. [Empuja a tu base de datos remota](#empujando-esquemas-de-tabla) con `astro db push --remote`. Esto agregará la nueva tabla y marcará la antigua como obsoleta. -4. Actualiza cualquier código de tu proyecto local para usar la nueva tabla en lugar de la antigua. Es posible que también necesites migrar datos a la nueva tabla. -5. Una vez que estés seguro de que la tabla antigua ya no se usa en tu proyecto, puedes eliminar el esquema de tu `config.ts`: - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. Empuja a tu base de datos remota nuevamente con `astro db push --remote`. La tabla antigua será eliminada, dejando solo la nueva tabla renombrada. - - -### Empujando datos de tabla - -Es posible que necesites empujar datos a tu base de datos remota para sembrar o migraciones de datos. Puedes crear un archivo `.ts` con el módulo `astro:db` para escribir consultas con seguridad de tipos. Luego, ejecuta el archivo contra tu base de datos remota usando el comando `astro db execute --remote`: - -Los siguientes Comentarios se pueden sembrar usando el comando `astro db execute db/seed.ts --remote`: - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: '¡Espero que te guste Astro DB!' }, - { authorId: 2, body: '¡Disfrútalo!' }, - ]) -} -``` - - - -Consulta la [referencia de la CLI](/es/guides/integrations-guide/db/#astro-db-cli-reference) para una lista completa de comandos. - - - -## Construyendo integraciones de Astro DB - -Las [integraciones de Astro](/es/reference/integrations-reference/) pueden extender proyectos de usuario con tablas adicionales de Astro DB y datos de semilla. - -Usa el método `extendDb()` en el hook `astro:db:setup` para registrar configuraciones adicionales de Astro DB y archivos de semilla. -El ayudante `defineDbIntegration()` proporciona soporte de TypeScript y autocompletado para el hook `astro:db:setup`. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'mi-integracion-impulsada-por-astro-db', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // Otros hooks de integración... - }, - }); -} -``` - -Los archivos de [configuración](#define-tu-base-de-datos) y [semilla](#sembrar-tu-base-de-datos-para-desarrollo) de integración siguen el mismo formato que sus equivalentes definidos por el usuario. - -### Operaciones con seguridad de tipos en integraciones - -Mientras trabajas en integraciones, es posible que no puedas beneficiarte de los tipos de tabla generados por Astro exportados desde `astro:db`. -Para seguridad de tipos completa, usa la utilidad `asDrizzleTable()` para crear un objeto de referencia de tabla que puedas usar para operaciones de base de datos. - -Por ejemplo, dada una integración configurando la siguiente tabla de base de datos `Pets`: - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -El archivo de semilla puede importar `Pets` y usar `asDrizzleTable()` para insertar filas en tu tabla con verificación de tipos: - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -El valor devuelto por `asDrizzleTable('Pets', Pets)` es equivalente a `import { Pets } from 'astro:db'`, pero está disponible incluso cuando la generación de tipos de Astro no puede ejecutarse. -Puedes usarlo en cualquier código de integración que necesite consultar o insertar en la base de datos. - -## Migrar de Astro Studio a Turso - - - -1. En el [panel de control de Studio](https://studio.astro.build/), navega al proyecto que deseas migrar. En la pestaña de configuración, usa el botón "Exportar Base de Datos" para descargar un volcado de tu base de datos. -2. Sigue las instrucciones oficiales para [instalar la CLI de Turso](https://docs.turso.tech/cli/installation) y [registrarte o iniciar sesión](https://docs.turso.tech/cli/authentication) en tu cuenta de Turso. -3. Crea una nueva base de datos en Turso usando el comando `turso db create`. - ```sh - turso db create [nombre-de-la-base-de-datos] - ``` -4. Obtén la URL de la base de datos usando la CLI de Turso, y úsala como la variable de entorno `ASTRO_DB_REMOTE_URL`. - ```sh - turso db show [nombre-de-la-base-de-datos] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[tu-url-de-base-de-datos] - ``` -5. Crea un token para acceder a tu base de datos, y úsalo como la variable de entorno `ASTRO_DB_APP_TOKEN`. - ```sh - turso db tokens create [nombre-de-la-base-de-datos] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[tu-token-de-aplicación] - ``` -6. Empuja tu esquema de DB y metadatos a la nueva base de datos de Turso. - ```sh - astro db push --remote - ``` -7. Importa el volcado de base de datos del paso 1 en tu nueva DB de Turso. - ```sh - turso db shell [nombre-de-la-base-de-datos] < ./ruta/al/volcado.sql - ``` -8. Una vez que hayas confirmado que tu proyecto se conecta a la nueva base de datos, puedes eliminar de manera segura el proyecto de Astro Studio. - - diff --git a/src/content/docs/fr/guides/astro-db.mdx b/src/content/docs/fr/guides/astro-db.mdx deleted file mode 100644 index 69acf8a55f1dc..0000000000000 --- a/src/content/docs/fr/guides/astro-db.mdx +++ /dev/null @@ -1,795 +0,0 @@ ---- -title: 'Astro DB' -description: Apprenez à utiliser Astro DB, une base de données SQL entièrement gérée, conçue exclusivement pour Astro. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -Astro DB est une base de données SQL entièrement gérée conçue pour l'écosystème Astro. Développez localement dans Astro et déployez vers n'importe quelle base de données compatible libSQL. - -Astro DB est une solution complète pour configurer, développer et interroger vos données. Une base de données locale est créée dans `.astro/content.db` chaque fois que vous exécutez `astro dev` pour gérer vos données sans avoir besoin de Docker ou d'une connexion réseau. - -## Installation - -Installez [l'intégration `@astrojs/db`](/fr/guides/integrations-guide/db/) à l'aide de la commande intégrée `astro add` : - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## Définir votre base de données - -L'installation de `@astrojs/db` avec la commande `astro add` créera automatiquement un fichier `db/config.ts` dans votre projet où vous définirez vos tables de base de données : - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### Tables - -Dans Astro DB, les données sont stockées dans des tables SQL. Les tables structurent vos données en lignes et en colonnes, où les colonnes imposent le type de chaque valeur de ligne. - -Définissez vos tables dans votre fichier `db/config.ts` en fournissant la structure des données de votre base de données libSQL existante ou les données que vous collecterez dans une nouvelle base de données. Cela permettra à Astro de générer une interface TypeScript pour interroger cette table à partir de votre projet. Le résultat est une prise en charge complète de TypeScript lorsque vous accédez à vos données avec la saisie semi-automatique des propriétés et la vérification des types. - -Pour configurer une table de base de données, importez et utilisez les utilitaires `defineTable()` et `column` depuis `astro:db`. Ensuite, définissez un nom (sensible à la casse) pour votre table et le type de données dans chaque colonne. - -Cet exemple configure une table `Comment` avec les colonnes de texte requises pour `author` et `body` et la rend disponible pour votre projet via l'exportation `defineDb()`. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -Voir la [référence de configuration des tables](/fr/guides/integrations-guide/db/#référence-de-configuration-des-tables) pour une référence complète des options de table. - -### Colonnes - -Astro DB prend en charge les types de colonnes suivants : - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // Une chaîne de texte. - author: column.text(), - // Une valeur entière. - likes: column.number(), - // Une valeur vraie ou fausse. - flagged: column.boolean(), - // Valeurs de date et d'heure interrogées sous forme d'Objets JavaScript de type date. - published: column.date(), - // Un objet JSON non typé. - metadata: column.json(), - } -}); -``` - -Voir la [référence des colonnes de la table](/fr/guides/integrations-guide/db/#référence-de-configuration-des-tables) pour plus de détails. - -### Références des tables - -Les relations entre les tables sont un modèle courant dans la conception des bases de données. Par exemple, une table `Blog` peut être en relation étroite avec d'autres tables `Comment`, `Author`, et `Category`. - -Vous pouvez définir ces relations entre les tables et les enregistrer dans votre schéma de base de données à l'aide de **colonnes de référence**. Pour établir une relation, vous aurez besoin de : - -- Une **colonne identifiant** de la table référencée. Il s'agit généralement d'une colonne `id` avec la propriété `primaryKey`. -- Une colonne sur la table de base pour **stocker l'`id` référencé**. Celle-ci utilise la propriété `references` pour établir une relation. - -Cet exemple montre que la colonne `authorId` d'une table `Comment` fait référence à la colonne `id` d'une table `Author`. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## Alimenter votre base de données pour le développement - -En cours de développement, Astro utilisera la configuration de votre base de données pour générer des types locaux en fonction de vos schémas. Ces derniers seront générés à partir de votre fichier de départ à chaque démarrage du serveur de développement et vous permettront d'interroger et de travailler avec la forme de vos données avec la sûreté du typage et la saisie semi-automatique. - -Vous n'aurez pas accès aux données de production pendant le développement, sauf si vous vous [connectez à une base de données distante](#connexion-à-des-bases-de-données-distantes) pendant le développement. Cela protège vos données tout en vous permettant de tester et de développer avec une base de données fonctionnelle et la sûreté du typage. - -Pour introduire des données de développement à des fins de test et de débogage dans votre projet Astro, créez un fichier `db/seed.ts`. Importez à la fois l'objet `db` et vos tables définies dans `astro:db`. Puis insérez des données initiales dans chaque table. Ces données de développement doivent correspondre à la forme de votre schéma de base de données et de vos données de production. - -L'exemple suivant définit deux lignes de données de développement pour une table `Comment` et une table `Author` : - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Nous espérons que vous aimez Astro DB !' }, - { authorId: 2, body: 'Profitez-en !'}, - ]) -} -``` - -Votre serveur de développement redémarrera automatiquement votre base de données chaque fois que ce fichier sera modifié, en régénérant vos types et en initialisant ces données de développement à partir de `seed.ts` à chaque fois. - -## Connecter une base de données libSQL pour la production - -Astro DB peut se connecter à n'importe quelle base de données libSQL locale ou à n'importe quel serveur qui expose le protocole distant libSQL, qu'il soit géré ou auto-hébergé. - -Pour connecter Astro DB à une base de données libSQL, définissez les variables d'environnement suivantes obtenues auprès de votre fournisseur de base de données : - -- `ASTRO_DB_REMOTE_URL` : l'URL de connexion à l'emplacement de votre base de données libSQL locale ou distante. Cela peut inclure des [options de configuration d'URL](#options-de-configuration-durl-distantes) telles que la synchronisation et le chiffrement en tant que paramètres. -- `ASTRO_DB_APP_TOKEN` : le jeton d'authentification de votre serveur libSQL. Ceci est nécessaire pour les bases de données distantes et n'est pas nécessaire pour [les bases de données locales comme les fichiers ou les bases de données en mémoire](#schéma-durl-et-hôte). - -Selon votre service, vous pouvez avoir accès à une interface CLI ou à une interface web pour récupérer ces valeurs. La section suivante illustre la connexion à Turso et la définition de ces valeurs à titre d'exemple, mais vous êtes libre d'utiliser n'importe quel fournisseur. - -### Premiers pas avec Turso - -Turso est l'entreprise à l'origine de [libSQL](https://github.com/tursodatabase/libsql), le fork open source de SQLite qui alimente Astro DB. Ils fournissent une plate-forme de base de données libSQL entièrement gérée et sont entièrement compatibles avec Astro. - -Les étapes ci-dessous vous guideront tout au long du processus d'installation de la CLI de Turso, de connexion (ou d'inscription), de création d'une nouvelle base de données, d'obtention des variables d'environnement requises et de transmission du schéma à la base de données distante. - - - -1. Installez la [CLI de Turso](https://docs.turso.tech/cli/installation). - -2. [Connectez-vous ou inscrivez-vous](https://docs.turso.tech/cli/authentication) à Turso. - -3. Créez une nouvelle base de données. Dans cet exemple, le nom de la base de données est `andromeda`. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. Exécutez la commande `show` pour voir les informations sur la base de données nouvellement créée : - - ```sh "andromeda" - turso db show andromeda - ``` - - Copiez la valeur `URL` et définissez-la comme valeur pour `ASTRO_DB_REMOTE_URL`. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. Créez un nouveau jeton pour authentifier les requêtes vers la base de données : - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - Copiez la sortie de la commande et définissez-la comme valeur pour `ASTRO_DB_APP_TOKEN`. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. Transférez vos schéma et métadonnées de base de données vers la nouvelle base de données Turso. - - ```sh - astro db push --remote - ``` - -7. Félicitations, vous avez maintenant une base de données connectée ! Accordez-vous une pause. 👾 - - ```sh - turso relax - ``` - - - -Pour découvrir davantage de fonctionnalités de Turso, consultez la [documentation de Turso](https://docs.turso.tech). - -### Connexion à des bases de données distantes - -Astro DB vous permet de vous connecter à des bases de données locales et distantes. Par défaut, Astro utilise un fichier de base de données local pour les commandes `dev` et `build`, recréant des tables et insérant des données de développement à chaque fois. - -Pour vous connecter à une base de données distante hébergée, utilisez l'option `--remote`. Celle-ci permet un accès en lecture et en écriture à votre base de données distante, ce qui vous permet d'[accepter et de conserver les données utilisateur](#insérer) dans les environnements de production. - -Configurez votre commande de compilation pour utiliser l'option `--remote` : - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -Vous pouvez également utiliser l'option directement dans la ligne de commande : - -```bash -# Compiler avec une connexion à distance -astro build --remote - -# Développer avec une connexion à distance -astro dev --remote -``` - -:::caution -Soyez prudent lorsque vous utilisez `--remote` en développement. Cela entraîne la connexion à votre base de données de production en direct et toutes les modifications (insertions, mises à jour, suppressions) seront conservées. -::: - -L'option `--remote` utilise la connexion à la base de données distante à la fois localement pendant la compilation et sur le serveur. Assurez-vous de définir les variables d'environnement nécessaires à la fois dans votre environnement de développement local et sur votre plateforme de déploiement. De plus, vous devrez peut-être [configurer le mode web](/fr/guides/integrations-guide/db/#mode) pour les environnements d'exécution n'utilisant pas Node.js tels que Cloudflare Workers ou Deno. - -Lors du déploiement de votre projet Astro DB, assurez-vous que la commande de compilation de votre plate-forme de déploiement est définie sur `npm run build` (ou l'équivalent pour votre gestionnaire de paquets) pour utiliser l'option `--remote` configurée dans votre fichier `package.json`. - -### Options de configuration d'URL distantes - -La variable d'environnement `ASTRO_DB_REMOTE_URL` configure l'emplacement de votre base de données ainsi que d'autres options telles que la synchronisation et le chiffrement. - -#### Schéma d'URL et hôte - -libSQL prend en charge HTTP et WebSockets comme protocole de transport pour un serveur distant. Il prend également en charge l'utilisation d'un fichier local ou d'une base de données en mémoire. Ceux-ci peuvent être configurés à l'aide des schémas d'URL suivants dans l'URL de connexion : - -- `memory:` utilisera une base de données en mémoire. L'hôte doit être vide dans ce cas. -- `file:` utilisera un fichier local. L'hôte est le chemin d'accès au fichier (`file:path/to/file.db`). -- `libsql:` utilisera un serveur distant via le protocole préféré par la bibliothèque (cela peut être différent selon les versions). L'hôte est l'adresse du serveur (`libsql://your.server.io`). -- `http:` utilisera un serveur distant via HTTP. `https:` peut être utilisé pour activer une connexion sécurisée. L'hôte est le même que pour `libsql:`. -- `ws:` utilisera un serveur distant via WebSockets. `wss:` peut être utilisé pour activer une connexion sécurisée. L'hôte est le même que pour `libsql:`. - -Les détails de la connexion libSQL (par exemple, la clé de chiffrement, la réplication, l'intervalle de synchronisation) peuvent être configurés comme paramètres de requête dans l'URL de connexion à distance. - -Par exemple, pour qu'un fichier local chiffré fonctionne comme une réplique intégrée sur un serveur libSQL, vous pouvez définir les variables d'environnement suivantes : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -L'utilisation d'un fichier de base de données est une fonctionnalité avancée et des précautions doivent être prises lors du déploiement pour éviter de remplacer votre base de données et de perdre vos données de production. - -De plus, cette méthode ne fonctionnera pas dans les déploiements sans serveur, car le système de fichiers n’est pas conservé dans ces environnements. -::: - -#### `encryptionKey` - -libSQL prend en charge nativement les bases de données chiffrées. La transmission de ce paramètre de recherche activera le chiffrement à l'aide de la clé donnée : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -Les répliques intégrées sont une fonctionnalité des clients libSQL qui crée une copie synchronisée complète de votre base de données sur un fichier local ou en mémoire pour des lectures ultra-rapides. Les écritures sont envoyées vers une base de données distante définie sur `syncUrl` et synchronisées avec la copie locale. - -Utilisez cette propriété pour transmettre une URL de connexion distincte afin de transformer la base de données en une réplique intégrée d'une autre base de données. Cela ne doit être utilisé qu'avec les schémas `file:` et `memory:`. Le paramètre doit être codé au format URL. - -Par exemple, pour avoir une réplique intégrée en mémoire d'une base de données sur `libsql://votre.server.io`, vous pouvez définir l'URL de connexion comme suit : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -Intervalle en secondes entre les synchronisations de répliques intégrées. Par défaut, la synchronisation se fait uniquement au démarrage et après les écritures. - -Cette propriété n'est utilisée que lorsque `syncUrl` est également définie. Par exemple, pour configurer une réplique intégrée en mémoire afin qu'elle se synchronise toutes les minutes, définissez la variable d'environnement suivante : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## Interroger votre base de données - -Vous pouvez interroger votre base de données depuis n'importe quelle [page Astro](/fr/basics/astro-pages/#pages-astro) ou [point de terminaison](/fr/guides/endpoints/) ou [action](/fr/guides/actions/) de votre projet en utilisant l'ORM `db` et le constructeur de requêtes fourni. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB comprend un client intégré [Drizzle ORM](https://orm.drizzle.team/). Il n'y a pas d'installation ou de configuration manuelle requise pour utiliser le client. Le client Astro DB `db` est automatiquement configuré pour communiquer avec votre base de données (locale ou distante) lorsque vous lancez Astro. Il utilise la définition exacte de votre schéma de base de données pour des requêtes SQL avec sûreté du typage et des erreurs TypeScript lorsque vous référencez une colonne ou une table qui n'existe pas. - -### Sélectionner - -L'exemple suivant sélectionne toutes les lignes d'une table `Comment`. Cela renvoie le tableau complet des données de développement provenant de `db/seed.ts`, qui est alors disponible pour être utilisé dans votre modèle de page : - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Commentaires

- -{ - comments.map(({ author, body }) => ( -
-

Auteur : {author}

-

{body}

-
- )) -} -``` - -Consultez la [référence de l'API `select()` de Drizzle](https://orm.drizzle.team/docs/select) pour un aperçu complet. - -### Insérer - -Pour accepter les entrées de l'utilisateur, comme le traitement des demandes de formulaire et l'insertion de données dans votre base de données hébergée à distance, configurez votre projet Astro pour [un rendu à la demande](/fr/guides/on-demand-rendering/) et [ajoutez un adaptateur](/fr/guides/on-demand-rendering/#ajouter-un-adaptateur) pour votre environnement de déploiement. - -Cet exemple insère une ligne dans une table `Comment` sur la base d'une requête POST de formulaire analysée : - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // Analyser les données du formulaire - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const content = formData.get('content'); - if (typeof author === 'string' && typeof content === 'string') { - // Insérer les données du formulaire dans la table Comment - await db.insert(Comment).values({ author, content }); - } -} - -// Affiche la nouvelle liste des commentaires sur chaque demande -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -Vous pouvez également utiliser [Astro Actions](/fr/guides/actions/) pour insérer des données dans une table Astro DB. L'exemple suivant insère une ligne dans une table `Comment` à l'aide d'une action : - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // Les actions incluent la sûreté du typage avec Zod, supprimant ainsi le - // besoin de vérifier si typeof {value} === 'string' dans vos pages - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // Renvoie les commentaires mis à jour - return updatedComments; - }, - }), -}; -``` - - - -Consultez la [référence de l'API `insert()` de Drizzle](https://orm.drizzle.team/docs/insert) pour une vue d'ensemble complète. - - - -### Supprimer - -Vous pouvez également interroger votre base de données à partir d'un point de terminaison d'API. Cet exemple supprime une ligne d'une table `Comment` par le paramètre `id` : - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -Consultez la [référence de l'API `delete()` de Drizzle](https://orm.drizzle.team/docs/delete) pour un aperçu complet. - - - -### Filtrage - -Pour rechercher les résultats d'une table en fonction d'une propriété spécifique, utilisez [les options de Drizzle pour les sélections partielles](https://orm.drizzle.team/docs/select#partial-select). Par exemple, ajoutez [un appel à `.where()`](https://orm.drizzle.team/docs/select#filtering) à votre requête `select()` et passez la comparaison que vous voulez faire. - -L'exemple suivant recherche toutes les lignes d'une table `Comment` qui contiennent l'expression « Astro DB ». Utilisez [l'opérateur `like()`](https://orm.drizzle.team/docs/operators#like) pour vérifier si une phrase est présente dans le `body` : - - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Utilitaires de Drizzle - -Tous les utilitaires de Drizzle permettant de construire des requêtes sont exposés à partir du module `astro:db`. Cela inclut : - -- [Les opérateurs de filtre](https://orm.drizzle.team/docs/operators) comme `eq()` et `gt()` -- [Les aides à l'agrégation](https://orm.drizzle.team/docs/select#aggregations-helpers) comme `count()` -- [L'aide `sql`](https://orm.drizzle.team/docs/sql) pour écrire des requêtes SQL brutes - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### Les relations - -Vous pouvez interroger des données liées provenant de plusieurs tables à l'aide d'une liaison SQL. Pour créer une requête de liaison, ajoutez un opérateur de liaison à votre déclaration `db.select()`. Chaque fonction accepte une table à l'origine de la liaison et une condition pour faire correspondre les lignes entre les deux tables. - -Cet exemple utilise une fonction `innerJoin()` pour faire la liaison entre les auteurs de commmentaires (`Comment`) et leurs informations `Author` sur la base de la colonne `authorId`. Cette fonction retourne un tableau d'objets avec chaque ligne `Author` et `Comment` comme propriétés de premier niveau : - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Commentaires

- -{ - comments.map(({ Author, Comment }) => ( -
-

Auteur : {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -Voir la [référence de liaison Drizzle](https://orm.drizzle.team/docs/joins#join-types) pour tous les opérateurs de liaison disponibles et les options de configuration. - - - -### Transactions par paquets - -Toutes les requêtes de bases de données distantes sont effectuées sous la forme d'une requête réseau. Vous pouvez avoir besoin de regrouper les requêtes en une seule transaction lorsque vous effectuez un grand nombre de requêtes, ou de procéder à des retours en arrière automatiques en cas d'échec d'une requête. - -Cet exemple permet de lancer plusieurs lignes en une seule requête à l'aide de la méthode `db.batch()` : - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - let queries; - // Envoyez 100 exemples de commentaires dans votre base de données distante - // avec une seule demande de réseau. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -Voir la documentation [de `db.batch()` sur Drizzle](https://orm.drizzle.team/docs/batch-api) pour plus de détails. - - - -## Envoi des modifications vers votre base de données - -Vous pouvez transférer les modifications apportées pendant le développement vers votre base de données. - -### Pousser les schémas de table - -Votre schéma de table peut changer au fil du temps à mesure que votre projet se développe. Vous pouvez tester en toute sécurité les modifications de configuration localement et les transférer vers votre base de données distante lors du déploiement. - -Vous pouvez transférer les modifications de votre schéma local vers votre base de données distante via la CLI à l'aide de la commande `astro db push --remote` : - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -Cette commande vérifiera que vos modifications locales peuvent être effectuées sans perte de données et, si nécessaire, vous suggérera comment apporter des modifications en toute sécurité à votre schéma afin de résoudre les conflits. - -#### Pousser les changements majeurs de schéma - -:::danger -__Cela détruira votre base de données__. N'exécutez cette commande que si vous n'avez pas besoin de vos données de production. -::: - -Si vous devez modifier le schéma de votre table d'une manière incompatible avec vos données existantes hébergées sur votre base de données distante, vous devrez réinitialiser votre base de données de production. - -Pour pousser une mise à jour du schéma de table qui inclut un changement radical, ajoutez l'option `--force-reset` pour réinitialiser toutes les données de production : - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### Renommer des tables - -Il est possible de renommer une table après avoir transmis votre schéma à votre base de données distante. - -Si vous **n'avez pas de données de production importantes**, alors vous pouvez [réinitialiser votre base de données](#pousser-les-changements-majeurs-de-schéma) en utilisant l'option `--force-reset`. Celle-ci supprimera toutes les tables de la base de données et en créera de nouvelles afin qu'elles correspondent exactement à votre schéma actuel. - -Pour renommer une table tout en préservant vos données de production, vous devez effectuer une série de modifications non cassantes pour transférer votre schéma local vers votre base de données distante en toute sécurité. - -L'exemple suivant renomme une table `Comment` en `Feedback` : - - - -1. Dans le fichier de configuration de votre base de données, ajoutez la propriété `deprecated: true` à la table que vous voulez renommer : - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. Ajoutez un nouveau schéma de table (correspondant exactement aux propriétés de la table existante) avec le nouveau nom : - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -3. [Poussez vers votre base de données distante](#pousser-les-schémas-de-table) avec `astro db push --remote`. Cela ajoutera la nouvelle table et marquera l'ancienne comme obsolète. -4. Mettez à jour le code de votre projet local pour utiliser la nouvelle table au lieu de l'ancienne. Il se peut que vous deviez également migrer des données vers la nouvelle table. -5. Une fois que vous êtes sûr que l'ancienne table n'est plus utilisée dans votre projet, vous pouvez supprimer le schéma de votre `config.ts` : - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. Poussez à nouveau vers votre base de données distante avec `astro db push --remote`. L'ancienne table sera supprimée, ne laissant que la nouvelle table renommée. - - -### Pousser les données d'une table - -Vous devrez peut-être transférer des données vers votre base de données distante pour l'amorçage ou les migrations de données. Vous pouvez créer un fichier `.ts` avec le module `astro:db` pour écrire des requêtes avec sûreté du typage. Ensuite, exécutez le fichier sur votre base de données distante à l'aide de la commande `astro db execute --remote` : - -Les commentaires suivants peuvent être initiés à l'aide de la commande `astro db execute db/seed.ts --remote` : - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: "J'espère que vous aimerez Astro DB !" }, - { authorId: 2, body: 'Profitez !' }, - ]) -} -``` - - - -Consultez la [référence de la CLI](/fr/guides/integrations-guide/db/#référence-de-la-cli-dastro-db) pour une liste complète des commandes. - - - -## Construire des intégrations Astro DB - -Les [intégrations Astro](/fr/reference/integrations-reference/) permettent d'étendre les projets des utilisateurs avec des tables Astro DB supplémentaires et des données de départ. - -Utilisez la méthode `extendDb()` dans le hook `astro:db:setup` pour enregistrer des fichiers de configuration et de données initiales (_seed_) Astro DB supplémentaires. -L'aide `defineDbIntegration()` fournit la prise en charge de TypeScript et l'auto-complétion pour le hook `astro:db:setup`. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // Autres hooks d'intégration... - }, - }); -} -``` - -Les fichiers de [configuration](#définir-votre-base-de-données) et de [données initiales](#alimenter-votre-base-de-données-pour-le-développement) des intégrations suivent le même format que leurs équivalents définis par l'utilisateur. - -### Opérations avec sûreté du typage dans les intégrations - -Lorsque vous travaillez sur des intégrations, il se peut que vous ne puissiez pas bénéficier des types de table générés par Astro et exportés depuis `astro:db`. -Pour une sûreté totale du typage, utilisez l'utilitaire `asDrizzleTable()` pour créer un objet de référence de table que vous pouvez utiliser pour les opérations de base de données. - -Par exemple, dans le cas d'une intégration mettant en place la table de base de données `Pets` suivante : - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -Le fichier de données initiales (« seed ») peut importer `Pets` et utiliser `asDrizzleTable()` pour insérer des lignes dans votre table avec vérification du type : - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -La valeur retournée par `asDrizzleTable('Pets', Pets)` est équivalente à `import { Pets } from 'astro:db'`, mais elle est disponible même si la génération de type d'Astro ne peut pas fonctionner. -Vous pouvez l'utiliser dans tout code d'intégration qui doit interroger ou insérer dans la base de données. - - - - -### Migrer depuis Astro Studio vers Turso - - - -1. Dans le [tableau de bord de Studio](https://studio.astro.build/), accédez au projet que vous souhaitez migrer. Dans l'onglet Paramètres, utilisez le bouton « Exporter la base de données » pour télécharger une copie de votre base de données. -2. Suivez les instructions officielles pour [installer la CLI de Turso](https://docs.turso.tech/cli/installation) et [inscrivez-vous ou connectez-vous](https://docs.turso.tech/cli/authentication) à votre compte Turso. -3. Créez une nouvelle base de données sur Turso en utilisant la commande `turso db create`. - ```sh - turso db create [database-name] - ``` -4. Récupérez l'URL de la base de données à l'aide de Turso CLI et utilisez-la comme variable d'environnement `ASTRO_DB_REMOTE_URL`. - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. Créez un jeton pour accéder à votre base de données et utilisez-le comme variable d'environnement `ASTRO_DB_APP_TOKEN`. - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. Transférez votre schéma de base de données et vos métadonnées vers la nouvelle base de données Turso. - ```sh - astro db push --remote - ``` -7. Importez l'exportation de la base de données de l’étape 1 dans votre nouvelle base de données Turso. - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. Une fois que vous avez confirmé que votre projet se connecte à la nouvelle base de données, vous pouvez supprimer le projet en toute sécurité dans Astro Studio. - - diff --git a/src/content/docs/fr/guides/integrations-guide/db.mdx b/src/content/docs/fr/guides/integrations-guide/db.mdx index 99bca074f8b59..49e1674fbd8a4 100644 --- a/src/content/docs/fr/guides/integrations-guide/db.mdx +++ b/src/content/docs/fr/guides/integrations-guide/db.mdx @@ -1,393 +1,11 @@ --- -type: integration title: '@astrojs/db' description: "Apprenez à utiliser l'intégration @astrojs/db dans votre projet Astro." -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other i18nReady: true --- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -Astro DB est une base de données SQL entièrement gérée, conçue pour l'écosystème Astro : développez localement dans Astro et déployer vers n'importe quelle [base de données compatible libSQL](/fr/guides/astro-db/). - -Avec Astro DB, vous disposez d'un outil puissant, local et sûr pour interroger et modéliser le contenu comme une base de données relationnelle. - -Consultez le [guide Astro DB](/fr/guides/astro-db/) pour une utilisation complète et des exemples. - -## Installation - -Astro inclut une commande `astro add` pour automatiser l'installation des intégrations officielles. Si vous préférez, vous pouvez [installer les intégrations manuellement](/fr/guides/integrations-guide/mdx/#installation-manuelle) à la place. - -Exécutez l'une des commandes suivantes dans une nouvelle fenêtre de terminal. - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### Installation manuelle - -Si vous préférez configurer les choses vous-même à partir de zéro, ignorez `astro add` et suivez ces instructions pour installer Astro DB vous-même. - -##### 1. Installer l'intégration à partir de npm via un gestionnaire de paquets - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. Ajouter l'intégration à `astro.config.mjs` - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. Configurer votre base de données - -Créez un fichier `db/config.ts` à la racine de votre projet. Il s'agit d'un fichier spécial qu'Astro chargera automatiquement et utilisera pour configurer les tables de votre base de données. - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## Configuration - -### `mode` - -

- -**Type :** `'node' | 'web'`
-**Par défaut :** `'node'`
- -

- -Configure le pilote à utiliser pour se connecter à votre base de données en production. - -Par défaut, Astro DB utilise un pilote libSQL reposant sur Node.js pour les déploiements en production. Le mode `node` du pilote est suffisant pour la plupart des sites web hébergés ou auto-hébergés par Astro avec des environnements d'exécution Node.js. Cela vous permet de vous connecter à votre base de données via plusieurs protocoles, notamment `memory:`, `file:`, `ws:`, `wss:`, `libsql`, `http` et `https`, ainsi que d'accéder à des fonctionnalités plus avancées telles que les [répliques intégrées](/fr/guides/astro-db/#syncurl). - -Lors d'un déploiement dans un environnement serverless dans un environnement d'exécution autre que Node.js, comme Cloudflare Workers ou Deno, un pilote libSQL est disponible. Lors du déploiement à l'aide du mode `web`, vous pourrez établir des connexions web via `libsql`, `http` ou `https`. - -Pour utiliser le mode web du pilote libSQL pour les environnements n'utilisant pas Node.js, définissez la propriété `mode` dans la configuration de votre adaptateur : - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## Référence de configuration des tables - -### `columns` - -

- -**Type :** `ColumnsConfig` -

- -Les colonnes de la table sont configurées à l'aide de l'objet `columns` : - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -Les colonnes sont configurées en utilisant l'utilitaire `column`. `column` prend en charge les types suivants : - -- **`column.text(...)`** - Stocke du contenu textuel simple ou enrichi -- **`column.number(...)`** - Stocke des valeurs entières et des valeurs à virgule flottante -- **`column.boolean(...)`** - Stocke des valeurs vraies / fausses -- **`column.date(...)`** - Stocke les objets `Date`, analysés comme des chaînes ISO pour le stockage des données. -- **`column.json(...)`** - Stocke des blobs JSON arbitraires, analysés en tant que JSON stringifié pour le stockage des données - -Quelques valeurs de configuration sont communes à toutes les colonnes : - -- `primaryKey` - Définit une colonne `number` ou `text` comme identifiant unique. -- `optional` - Astro DB utilise `NOT NULL` pour toutes les colonnes par défaut. Définissez `optional` sur `true` pour autoriser les valeurs nulles. -- `default` - Définit la valeur par défaut pour les entrées nouvellement insérées. Ceci accepte soit une valeur statique, soit une chaîne de `sql` pour les valeurs générées comme les timestamps. -- `unique` - Marque une colonne comme unique. Cela permet d'éviter les valeurs dupliquées dans les entrées de la table. -- `references` - Fait référence à une table liée par une colonne. Cela établit une contrainte de clé étrangère, ce qui signifie que chaque valeur de colonne doit avoir une valeur correspondante dans la table référencée. - -Une colonne `texte` peut éventuellement définir une liste de chaînes de caractères litérales qui sera utilisée en tant qu'énumération pour la génération des types. Cependant, **aucune validation ne sera effectuée au moment de l'exécution**. La suppression, l'ajout et la modification de valeurs doivent être gérés dans le code de votre projet. - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// Définition de la table -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// Définition de type résultant -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**Type :** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -Les index de table sont utilisés pour améliorer la vitesse de recherche sur une colonne donnée ou une combinaison de colonnes. La propriété `indexes` accepte un tableau d'objets de configuration spécifiant les colonnes à indexer : - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -Cela générera un index unique sur les colonnes `authorId` et `published` avec le nom `Comment_authorId_published_idx`. - -Les options de configuration suivantes sont disponibles pour chaque index : - -- `on` - Une seule colonne ou un tableau de noms de colonnes à indexer. -- `unique` - Définir sur `true` pour imposer des valeurs uniques à travers les colonnes indexées. -- `name` (Optionnel) - Un nom personnalisé pour l'index unique. Il remplacera le nom généré par Astro basé sur les noms de la table et de la colonne indexée (par exemple `Comment_authorId_published_idx`). Les noms personnalisés sont globaux, il faut donc s'assurer que les noms d'index n'entrent pas en conflit entre les tables. - -### `foreignKeys` - -

- -**Type :** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys` est une API avancée pour relier plusieurs colonnes d'une table. Si vous n'avez besoin de référencer qu'une seule colonne, essayez d'utiliser [la propriété `references` de la colonne](#columns). +:::caution[Deprecated] +The Astro DB integration has been deprecated in Astro v7.0 and is no longer maintained. +If you were using this integration in your project, we recommend migrating to a third-party library for database functionality. See the [Astro v7.0 migration guide](/fr/guides/upgrade-to/v7/#removed-astrojsdb) for more details and recommendations on how to update your project. ::: - -Les clés étrangères sont utilisées pour établir une relation entre deux tables. La propriété `foreignKeys` accepte un tableau d'objets de configuration qui peuvent relier une ou plusieurs colonnes entre les tables : - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -Chaque objet de configuration de clé étrangère accepte les propriétés suivantes : - -- `columns` - Un tableau de noms de colonnes à associer à la table référencée. -- `references` - Une fonction qui renvoie un tableau de colonnes de la table référencée. - -## Référence de la CLI d'Astro DB - -Astro DB inclut un ensemble de commandes CLI pour interagir pour interagir avec votre base de données locale et compatible libSQL. - -Ces commandes sont appelées automatiquement lors de l'utilisation d'une action CI GitHub, et peuvent être appelées manuellement en utilisant la CLI `astro db`. - -### `astro db push` - -**Options :** - -- `--db-app-token ` Fournir directement le jeton de l'application de base de données distante au lieu de `ASTRO_DB_APP_TOKEN`. -- `--dry-run` Imprimer les instructions SQL générées sans les appliquer. -- `--force-reset` Réinitialiser toutes les données de production si une modification du schéma avec rupture de compatibilité est nécessaire. -- `--remote` Transférer vers votre base de données distante plutôt que vers le fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Transférez en toute sécurité les modifications apportées à la configuration de la base de données dans la base de données de votre projet. Cela vérifiera tout risque de perte de données et vous guidera sur les étapes de migration recommandées. Utilisez `--remote` pour appliquer les modifications à votre base de données distante. Si une modification de schéma avec rupture de compatibilité est nécessaire, utilisez `--force-reset` pour réinitialiser toutes les données de production. - -### `astro db verify` - -**Options :** - -- `--db-app-token ` Fournir directement le jeton de l'application de base de données distante au lieu de `ASTRO_DB_APP_TOKEN`. -- `--json` Imprimer un résultat JSON lisible par machine à partir de `verify`. -- `--remote` Comparer avec votre base de données distante plutôt qu'avec le fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Compare votre schéma local à la base de données distante afin de vérifier les éventuelles différences entre les configurations de vos bases de données locale et distante. Cette opération est exécutée automatiquement par `astro db push`. - -`verify` comparera votre fichier `db/config.ts` local avec la base de données distante et vous avertira si des modifications sont détectées. Elle renverra un code d'erreur si des modifications sont nécessaires ou non sécurisées, ce qui la rend utile pour l'intégration continue (CI). - -### `astro db execute ` - -**Options :** - -- `--db-app-token ` Fournir directement le jeton de l'application de base de données distante au lieu de `ASTRO_DB_APP_TOKEN`. -- `--remote` Exécuter cette commande sur votre base de données compatible libSQL. Omettre cette option pour exécuter la commande sur votre fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Exécute un fichier `.ts` ou `.js` pour lire ou écrire dans votre base de données. Cette commande accepte un chemin de fichier comme argument, et prend en charge l'utilisation du module `astro:db` pour écrire des requêtes sûres. Utilisez l'option `--remote` pour exécuter sur votre base de données compatible libSQL, ou ignorez l'option pour lancer l'exécution sur votre fichier de base de données local. Consultez [alimenter les données de développement](/fr/guides/astro-db/#alimenter-votre-base-de-données-pour-le-développement) pour un exemple de fichier. - -### `astro db shell --query ` - -**Options :** - -- `--query` Requête SQL brute à exécuter. -- `--remote` Exécuter cette commande sur votre base de données compatible libSQL. Omettre cette option pour exécuter la commande sur votre fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Exécute une requête SQL brute sur votre base de données. - -L'exemple suivant sélectionne toutes les lignes d'une table `Comment` dans une base de données distante : - -```sh -npx astro db shell --query "SELECT * FROM Comment;" --remote -``` - -## Référence des utilitaires d'Astro DB - -Les utilitaires suivants sont importés depuis le module `astro:db` : - -```ts -import { - isDbError, - getDbError -} from "astro:db"; -``` - -### `isDbError()` - -

- -**Type :** `(err: unknown) => boolean`
- -

- -Vérifie si une erreur est une exception de la base de données libSQL. Il peut s'agir d'une erreur de contrainte de clé étrangère lors de l'utilisation de références, ou de champs manquants lors de l'insertion de données. Vous pouvez combiner `isDbError()` avec un bloc try/catch pour gérer les erreurs de base de données dans votre application : - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`Impossible d'insérer un commentaire avec l'id ${id}\n\n${e.message}`, { status: 400 }); - } - return new Response("Une erreur inattendue s'est produite", { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` - -### `getDbError()` - -

- -**Type :** `(err: unknown) => LibsqlError | undefined`
- -

- -Parcourt la chaîne de causes d'une erreur pour trouver l'exception sous-jacente de la base de données libSQL. Elle renvoie `LibsqlError` ou `undefined` si l'erreur ne provient pas de LibSQL. Cela est utile lorsqu'une autre erreur (par exemple, `DrizzleQueryError`) peut envelopper l'erreur de base de données. - -L'exemple suivant extrait l'erreur de base de données d'une exception interceptée et renvoie le code d'erreur et le message dans la réponse : - -```ts title="src/pages/api/comment/[id].ts" "getDbError" -import { getDbError } from 'astro:db'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - const dbError = getDbError(e); - if (dbError) { - return new Response(`Erreur de base de données : ${dbError.code}\n\n${dbError.message}`, { status: 400 }); - } - return new Response("Une erreur inattendue s'est produite", { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` diff --git a/src/content/docs/fr/reference/cli-reference.mdx b/src/content/docs/fr/reference/cli-reference.mdx index b61e2d66d5ddf..c6f034a6227a0 100644 --- a/src/content/docs/fr/reference/cli-reference.mdx +++ b/src/content/docs/fr/reference/cli-reference.mdx @@ -266,7 +266,6 @@ Exécuter `astro dev`, `astro build` ou `astro check` exécutera également la c Génère des types TypeScript pour tous les modules Astro. Cela configure un [fichier `.astro/types.d.ts`](/fr/guides/typescript/#configuration) pour l'inférence de type et définit des modules pour les fonctionnalités qui s'appuient sur des types générés : - Le module `astro:content` pour l'[API des collections de contenus](/fr/guides/content-collections/). -- Le module `astro:db` pour [Astro DB](/fr/guides/astro-db/). - Le module `astro:env` pour [Astro Env](/fr/guides/environment-variables/). - Le module `astro:actions` pour [Astro Actions](/fr/guides/actions/) diff --git a/src/content/docs/ko/guides/astro-db.mdx b/src/content/docs/ko/guides/astro-db.mdx deleted file mode 100644 index b62e1e4c1e343..0000000000000 --- a/src/content/docs/ko/guides/astro-db.mdx +++ /dev/null @@ -1,793 +0,0 @@ ---- -title: 'Astro DB' -description: Astro 전용으로 설계된 완전 관리형 SQL 데이터베이스인 Astro DB를 사용하는 방법을 알아보세요. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -Astro DB는 Astro 생태계를 위해 설계된 완전 관리형 SQL 데이터베이스입니다. Astro에서 로컬로 개발하여 모든 libSQL 호환 데이터베이스에 배포하세요. - -Astro DB는 데이터를 구성, 개발, 쿼리할 수 있는 완벽한 솔루션입니다. Docker나 네트워크 연결 없이도 데이터를 관리하기 위해 `astro dev`를 실행할 때마다 로컬 데이터베이스가 `.astro/content.db`에 생성됩니다. - -## 설치 - -내장된 `astro add` 명령을 사용하여 [`@astrojs/db` 통합](/ko/guides/integrations-guide/db/)을 설치합니다: - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## 데이터베이스 정의 - -`astro add` 명령으로 `@astrojs/db`를 설치하면 프로젝트에 데이터베이스 테이블을 정의할 `db/config.ts` 파일이 자동으로 생성됩니다: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### 테이블 - -Astro DB의 데이터는 SQL 테이블을 사용하여 저장됩니다. 테이블은 데이터를 행과 열로 구조화하며, 여기서 열은 각 행 값의 타입을 적용합니다. - -기존 libSQL 데이터베이스의 데이터 구조 또는 새 데이터베이스에서 수집할 데이터를 제공하여 `db/config.ts` 파일에 테이블을 정의하세요. 이렇게 하면 Astro가 프로젝트에서 해당 테이블을 쿼리하기 위한 TypeScript 인터페이스를 생성할 수 있습니다. 결과적으로 데이터에 액세스할 때 속성 자동 완성 및 타입 검사를 통해 완전한 TypeScript 지원이 제공됩니다. - -데이터베이스 테이블을 구성하려면 `astro:db`에서 `defineTable()` 및 `column` 유틸리티를 가져와 사용하세요. 그런 다음 테이블의 이름 (대소문자 구분)과 각 열의 데이터 타입을 정의합니다. - -이 예시에서는 `author` 및 `body`에 대한 필수 텍스트 열이 있는 `Comment` 테이블을 구성합니다. 그런 다음 `defineDb()` 내보내기를 통해 프로젝트에서 사용할 수 있도록 합니다. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -테이블 옵션에 대한 전체 참조는 [테이블 구성 참조](/ko/guides/integrations-guide/db/#테이블-구성-참조)를 확인하세요. - -### 열 (Columns) - -Astro DB는 다음 열 타입을 지원합니다. - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // 텍스트 문자열입니다. - author: column.text(), - // 정수 값입니다. - likes: column.number(), - // 참 또는 거짓 값입니다. - flagged: column.boolean(), - // JavaScript Date 객체로 쿼리되는 날짜/시간 값입니다. - published: column.date(), - // 타입이 설정되지 않은 JSON 객체입니다. - metadata: column.json(), - } -}); -``` - -자세한 내용은 [테이블 열 참조](/ko/guides/integrations-guide/db/#테이블-구성-참조)를 확인하세요. - -### 테이블 참조 - -테이블 간 관계는 데이터베이스 디자인의 일반적인 패턴입니다. 예를 들어, `Blog` 테이블은 `Comment`, `Author` 및 `Category`의 다른 테이블과 밀접하게 관련될 수 있습니다. - -테이블 간 관계를 정의하고 **참조 열 (reference columns)** 을 사용하여 데이터베이스 스키마에 저장할 수 있습니다. 관계를 구축하려면 다음이 필요합니다. - -- 참조 테이블의 **식별자 열 (identifier column)** 이 필요합니다. 이는 일반적으로 `primaryKey` 속성이 있는 `id` 열입니다. -- **참조된 `id`를 저장하기 위한 기본 테이블의 열** 이 필요합니다. 이는 관계를 설정하기 위해 `references` 속성을 사용합니다. - -이 예시에서는 `Author` 테이블의 `id` 열을 참조하는 `Comment` 테이블의 `authorId` 열을 보여줍니다. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## 개발 모드에서 데이터베이스 시드 - -개발 모드에서 Astro는 DB 구성을 사용하여 스키마에 따라 로컬 타입을 생성합니다. 이는 개발 서버가 시작될 때마다 시드 파일에서 새로 생성되며 타입 안전성 및 자동 완성을 통해 데이터 형태를 쿼리하고 작업할 수 있습니다. - -개발 모드에서 [원격 데이터베이스에 연결](#원격-데이터베이스에-연결)하지 않으면 개발 중에 프로덕션 데이터에 액세스할 수 없습니다. 이렇게 하면 데이터를 보호하는 동시에 타입 안전성이 보장된 작동 중인 데이터베이스로 테스트하고 개발할 수 있습니다. - -테스트 및 디버깅을 위해 개발 데이터를 Astro 프로젝트에 시드하려면 `db/seed.ts` 파일을 생성합니다. `db` 객체와 `astro:db`에 정의된 테이블을 모두 가져옵니다. 각 테이블에 초기 데이터를 `insert` 합니다. 이 개발 데이터는 데이터베이스 스키마 및 프로덕션 데이터의 형식과 일치해야 합니다. - -다음 예시에서는 `Comment` 테이블과 `Author` 테이블에 대한 개발 데이터의 두 행을 정의합니다. - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!'}, - ]) -} -``` - -개발 서버는 이 파일이 변경될 때마다 자동으로 데이터베이스를 다시 시작하여 타입을 재생성하고 매번 `seed.ts`에서 이 개발 데이터를 새로 시드합니다. - -## 프로덕션용 libSQL 데이터베이스 연결 - -Astro DB는 관리형 또는 자체 호스팅에 관계없이 모든 로컬 libSQL 데이터베이스 또는 libSQL 원격 프로토콜을 노출하는 모든 서버에 연결할 수 있습니다. - -Astro DB를 libSQL 데이터베이스에 연결하려면 데이터베이스 제공업체에서 얻은 다음 환경 변수를 설정하세요: - -- `ASTRO_DB_REMOTE_URL`: 로컬 또는 원격 libSQL DB의 위치에 대한 연결 URL입니다. 여기에는 동기화 및 암호화와 같은 [URL 구성 옵션](#원격-url-구성-옵션)이 매개변수로 포함될 수 있습니다. -- `ASTRO_DB_APP_TOKEN`: libSQL 서버의 인증 토큰입니다. 이는 원격 데이터베이스에 필요하며 [파일 또는 인메모리와 같은 로컬 DB](#url-스킴-및-호스트) 데이터베이스에는 필요하지 않습니다. - -서비스에 따라 CLI 또는 웹 UI에 액세스하여 이러한 값을 검색할 수 있습니다. 다음 섹션에서는 Turso에 연결하여 이러한 값을 설정하는 방법을 예시로 보여드리지만, 어떤 제공업체를 사용하든 자유롭게 사용할 수 있습니다. - -### Turso로 시작하기 - -Turso는 Astro DB를 구동하는 SQLite의 오픈 소스 포크인 [libSQL](https://github.com/tursodatabase/libsql)을 개발한 회사입니다. 완전히 관리되는 libSQL 데이터베이스 플랫폼을 제공하며 Astro와 완벽하게 호환됩니다. - -아래 단계는 Turso CLI 설치, 로그인 (또는 가입), 새 데이터베이스 생성, 필요한 환경 변수 가져오기, 스키마를 원격 데이터베이스에 푸시하는 과정을 안내합니다. - - - -1. [Turso CLI](https://docs.turso.tech/cli/installation)를 설치합니다. - -2. Turso에 [로그인 또는 가입](https://docs.turso.tech/cli/authentication)합니다. - -3. 새 데이터베이스를 생성합니다. 이 예시에서 데이터베이스 이름은 `andromeda`입니다. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. `show` 명령을 실행하여 새로 생성된 데이터베이스에 대한 정보를 확인합니다: - - ```sh "andromeda" - turso db show andromeda - ``` - - `URL` 값을 복사하여 `ASTRO_DB_REMOTE_URL`의 값으로 설정합니다. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. 데이터베이스에 대한 요청을 인증할 새 토큰을 생성합니다: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - 명령의 출력을 복사하여 `ASTRO_DB_APP_TOKEN`의 값으로 설정합니다. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. DB 스키마 및 메타데이터를 새 Turso 데이터베이스로 푸시합니다. - - ```sh - astro db push --remote - ``` - -7. 축하합니다, 이제 데이터베이스가 연결되었습니다! 이제 휴식을 취하세요. 👾 - - ```sh - turso relax - ``` - - - -Turso의 더 많은 기능을 살펴보려면 [Turso 문서](https://docs.turso.tech)를 확인하세요. - -### 원격 데이터베이스에 연결 - -Astro DB를 사용하면 로컬 및 원격 데이터베이스에 모두 연결할 수 있습니다. 기본적으로 Astro는 `dev` 및 `build` 명령에 로컬 데이터베이스 파일을 사용하여 테이블을 다시 생성하고 매번 개발 시드 데이터를 삽입합니다. - -호스팅된 원격 데이터베이스에 연결하려면 `--remote` 플래그를 사용합니다. 이 플래그를 사용하면 원격 데이터베이스에 대한 읽기 및 쓰기 액세스가 모두 가능하므로 프로덕션 환경에서 [사용자 데이터를 허용 및 유지](#insert)할 수 있습니다. - -`--remote` 플래그를 사용하도록 빌드 명령을 구성합니다: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -명령줄에서 직접 플래그를 사용할 수도 있습니다: - -```bash -# 원격 연결을 통한 빌드 -astro build --remote - -# 원격 연결을 통한 개발 -astro dev --remote -``` - -:::caution -개발 모드에서 `--remote`를 사용할 때는 주의하세요. 이렇게 하면 라이브 프로덕션 데이터베이스에 연결되며 모든 변경 사항 (삽입, 업데이트, 삭제)이 유지됩니다. -::: - -`--remote` 플래그는 로컬 빌드와 서버에서 모두 원격 DB에 대한 연결을 사용합니다. 로컬 개발 환경과 배포 플랫폼 모두에서 필요한 환경 변수를 설정했는지 확인하세요. 또한 Cloudflare Workers나 Deno와 같은 Node.js가 아닌 런타임 환경에서는 [웹 모드를 구성](/ko/guides/integrations-guide/db/#mode)해야 할 수도 있습니다. - -Astro DB 프로젝트를 배포할 때, 배포 플랫폼의 빌드 명령이 `package.json`에 구성된 `--remote` 플래그를 활용하도록 `npm run build` (또는 패키지 관리자에 상응하는 명령어)로 설정되어 있는지 확인하세요. - -### 원격 URL 구성 옵션 - -`ASTRO_DB_REMOTE_URL` 환경 변수는 데이터베이스의 위치와 동기화 및 암호화와 같은 기타 옵션을 구성합니다. - -#### URL 스킴 및 호스트 - -libSQL은 원격 서버의 전송 프로토콜로 HTTP와 WebSockets을 모두 지원합니다. 또한 로컬 파일이나 인메모리 DB 사용도 지원합니다. 이러한 프로토콜은 연결 URL에서 다음 URL 스킴을 사용하여 구성할 수 있습니다: - -- `memory:` 인메모리 DB를 사용합니다. 이 경우 호스트는 비어 있어야 합니다. -- `file:` 로컬 파일을 사용합니다. 호스트는 파일 경로입니다 (`file:path/to/file.db`). -- `libsql:` 라이브러리에서 선호하는 프로토콜을 통해 원격 서버를 사용합니다 (버전에 따라 다를 수 있음). 호스트는 서버의 주소 (`libsql://your.server.io`)입니다. -- `http:` HTTP를 통해 원격 서버를 사용합니다. 보안 연결을 사용하려면 `https:`를 사용할 수 있습니다. 호스트는 `libsql:`와 동일합니다. -- `ws:` WebSockets을 통해 원격 서버를 사용합니다. `wss:`를 사용하여 보안 연결을 활성화할 수 있습니다. 호스트는 `libsql:`와 동일합니다. - -libSQL 연결의 세부 정보 (예: 암호화 키, 복제, 동기화 간격)는 원격 연결 URL에서 쿼리 매개변수로 구성될 수 있습니다. - -예를 들어 암호화된 로컬 파일이 libSQL 서버에 임베디드 복제본으로 작동하도록 하려면 다음 환경 변수를 설정하면 됩니다: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -데이터베이스 파일을 사용하는 것은 고급 기능이므로 배포 시 데이터베이스가 재정의되어 프로덕션 데이터가 손실되지 않도록 주의해야 합니다. - -또한 서버리스 배포에서는 파일 시스템이 유지되지 않으므로 이 방법은 작동하지 않습니다. -::: - -#### `encryptionKey` - -libSQL은 암호화된 데이터베이스를 기본적으로 지원합니다. 이 검색 매개변수를 전달하면 지정된 키를 사용하여 암호화를 활성화합니다: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -임베디드 복제본은 초고속 읽기를 위해 로컬 파일이나 메모리에 데이터베이스의 전체 동기화 복사본을 저장할 수 있는 libSQL 클라이언트의 기능입니다. 쓰기는 `syncUrl`에 정의된 원격 데이터베이스로 전송되어 로컬 복사본과 동기화됩니다. - -이 속성을 사용하여 별도의 연결 URL을 전달하여 데이터베이스를 다른 데이터베이스의 임베디드 복제본으로 전환할 수 있습니다. 이 속성은 `file:` 및 `memory:` 스킴에서만 사용해야 합니다. 매개변수는 URL로 인코딩되어야 합니다. - -예를 들어 데이터베이스의 인메모리 임베디드 복제본을 `libsql://your.server.io`에 만들려면 연결 URL을 다음과 같이 설정할 수 있습니다. - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -임베디드 복제본 동기화 간격 (초)입니다. 기본적으로 시작 시와 쓰기 후에만 동기화됩니다. - -이 속성은 `syncUrl`도 설정된 경우에만 사용됩니다. 예를 들어 인메모리 임베디드 복제본이 매분 동기화되도록 설정하려면 다음 환경 변수를 설정합니다: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## 데이터베이스 쿼리 - -제공된 db ORM 및 쿼리 빌더를 사용하여 프로젝트의 모든 [Astro 페이지](/ko/basics/astro-pages/#astro-페이지), [엔드포인트](/ko/guides/endpoints/), 또는 [액션](/ko/guides/actions/)에서 데이터베이스를 쿼리할 수 있습니다. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB에는 [Drizzle ORM](https://orm.drizzle.team/) 클라이언트가 내장되어 있습니다. 클라이언트를 사용하는 데 필요한 설정이나 수동 구성이 없습니다. Astro DB의 `db` 클라이언트는 Astro를 실행할 때 데이터베이스 (로컬 또는 원격)와 통신하도록 자동으로 구성됩니다. 존재하지 않는 열이나 테이블을 참조할 때, TypeScript 오류가 발생한 타입 안정성을 갖춘 SQL 쿼리에 대해 정확한 데이터베이스 스키마 정의를 사용합니다. - -### Select - -다음 예시에서는 `Comment` 테이블의 모든 행을 선택합니다. 그러면 페이지 템플릿에서 사용할 수 있는 `db/seed.ts` 파일에서 시드된 개발 데이터의 전체 배열이 반환됩니다. - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comments

- -{ - comments.map(({ author, body }) => ( -
-

Author: {author}

-

{body}

-
- )) -} -``` - -전체 개요는 [Drizzle `select()` API 참조](https://orm.drizzle.team/docs/select)를 확인하세요. - -### Insert - -양식 요청 처리 및 원격 호스팅 데이터베이스에 데이터 삽입과 같은 사용자 입력을 허용하려면 Astro 프로젝트에 [주문형 렌더링](/ko/guides/on-demand-rendering/)을 구성하고 배포 환경에 [SSR 어댑터를 추가](/ko/guides/on-demand-rendering/#어댑터-추가)하세요. - -이 예시에서는 구문 분석된 양식 POST 요청을 기반으로 `Comment` 테이블에 행을 삽입합니다. - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // 양식 데이터 구문 분석 - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // Comment 테이블에 양식 데이터 삽입 - await db.insert(Comment).values({ author, body }); - } -} - -// 각 요청에 대해 새로운 comments 목록을 렌더링 -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -[Astro 액션](/ko/guides/actions/)을 사용하여 Astro DB 테이블에 데이터를 삽입할 수도 있습니다. 다음은 액션을 사용하여 `Comment` 테이블에 행을 삽입하는 예시입니다: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // 액션에는 Zod의 타입 안정성이 포함되어 있으므로 - // 페이지에서 typeof {value} === 'string'인지 확인할 필요가 없습니다. - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // 업데이트된 comments를 반환합니다. - return updatedComments; - }, - }), -}; -``` - - - -전체 개요는 [Drizzle `insert()` API 참조](https://orm.drizzle.team/docs/insert)를 확인하세요. - - - -### Delete - -API 엔드포인트에서 데이터베이스를 쿼리할 수도 있습니다. 이 예시에서는 `id` 매개변수를 사용하여 `Comment` 테이블에서 행을 삭제합니다: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -전체 개요는 [Drizzle `delete()` API 참조](https://orm.drizzle.team/docs/delete)를 확인하세요. - - - -### 필터링 - -특정 속성으로 테이블 결과를 쿼리하려면 [부분 선택을 위한 Drizzle 옵션](https://orm.drizzle.team/docs/select#partial-select)을 사용하세요. 예를 들어, `select()` 쿼리에 [`.where()` 호출](https://orm.drizzle.team/docs/select#filtering)을 추가하고 원하는 비교를 전달합니다. - -다음 예시에서는 "Astro DB"라는 문구가 포함된 `Comment` 테이블의 모든 행을 쿼리합니다. `body`에 문구가 있는지 확인하려면 [`like()` 연산자](https://orm.drizzle.team/docs/operators#like)를 사용하세요. - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Drizzle 유틸리티 - -쿼리 작성을 위한 모든 Drizzle 유틸리티는 `astro:db` 모듈에서 노출됩니다. 여기에는 다음이 포함됩니다. - -- [필터 연산자](https://orm.drizzle.team/docs/operators) 예: `eq()` 및 `gt()` -- [집계 도우미](https://orm.drizzle.team/docs/select#aggregations-helpers) 예: `count()` -- [`sql` 도우미](https://orm.drizzle.team/docs/sql) - 원시 SQL 쿼리 작성 - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### 관계 - -SQL join을 사용하여 여러 테이블에서 관련 데이터를 쿼리할 수 있습니다. join 쿼리를 생성하려면 `db.select()` 문을 join 연산자로 확장하세요. 각 함수는 join할 테이블과 두 테이블 사이의 행을 일치시키는 조건을 인자로 전달받습니다. - -이 예시에서는 `innerJoin()` 함수를 사용하여 `authorId` 열을 기반으로 `Comment`의 authors를 관련 `Author` 정보와 join합니다. 그러면 각 `Author` 및 `Comment` 행이 최상위 속성인 객체 배열이 반환됩니다. - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comments

- -{ - comments.map(({ Author, Comment }) => ( -
-

Author: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -사용 가능한 모든 join 연산자 및 구성 옵션은 [Drizzle join 참조](https://orm.drizzle.team/docs/joins#join-types)를 확인하세요. - - - -### 일괄 트랜잭션 - -모든 원격 데이터베이스 쿼리는 네트워크 요청으로 이루어집니다. 많은 수의 쿼리를 수행할 때 쿼리를 단일 트랜잭션으로 함께 "일괄 처리"하거나 쿼리가 실패할 경우 자동 롤백을 수행해야 할 수도 있습니다. - -이 예시에서는 `db.batch()` 메서드를 사용하여 단일 요청에 여러 행을 시드합니다. - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // 단일 네트워크 요청으로 원격 데이터베이스에 100개의 샘플 comments를 시드합니다. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -자세한 내용은 [Drizzle `db.batch()`](https://orm.drizzle.team/docs/batch-api) 문서를 참조하세요. - - - -## 데이터베이스에 변경 사항 푸시하기 - -개발 중에 변경한 내용을 데이터베이스에 푸시할 수 있습니다. - -### 테이블 스키마 푸시 - -프로젝트가 성장하면서 테이블 스키마는 시간이 지남에 따라 변경될 수 있습니다. 구성 변경 사항을 로컬에서 안전하게 테스트하고 배포할 때 원격 데이터베이스로 푸시할 수 있습니다. - -`astro db push --remote` 명령을 사용하여 CLI를 통해 로컬 스키마 변경 사항을 원격 데이터베이스로 푸시할 수도 있습니다. - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -이 명령은 데이터 손실 없이 로컬 변경이 이루어질 수 있는지 확인하고 필요한 경우 충돌을 해결하기 위해 스키마를 안전하게 변경하는 방법을 제안합니다. - -#### 주요 스키마 변경 사항 푸시 - -:::danger -__이렇게 하면 데이터베이스가 파괴됩니다__. 프로덕션 데이터가 필요하지 않은 경우에만 이 명령을 수행하세요. -::: - -원격 데이터베이스에서 호스팅되는 기존 데이터와 호환되지 않는 방식으로 테이블 스키마를 변경해야 하는 경우 프로덕션 데이터베이스를 초기화해야 합니다. - -주요 변경 사항이 포함된 테이블 스키마 업데이트를 푸시하려면 `--force-reset` 플래그를 추가하여 모든 프로덕션 데이터를 초기화하세요. - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### 테이블 이름 변경 - -스키마를 원격 데이터베이스로 푸시한 후 테이블 이름을 변경할 수 있습니다. - -**중요한 프로덕션 데이터가 없는** 경우 `--force-reset` 플래그를 사용하여 [데이터베이스를 초기화](#주요-스키마-변경-사항-푸시)할 수 있습니다. 이 플래그는 데이터베이스의 모든 테이블을 삭제하고 현재 스키마와 정확히 일치하는 새 테이블을 생성합니다. - -프로덕션 데이터를 보존하면서 테이블 이름을 변경하려면, 기존 기능을 중단하지 않는 변경을 수행하여 로컬 스키마를 원격 데이터베이스에 안전하게 푸시해야 합니다. - -다음 예시에서는 테이블의 이름을 `Comment`에서 `Feedback`으로 변경합니다. - - - -1. 데이터베이스 구성 파일에서 이름을 바꾸려는 테이블에 `deprecated: true` 속성을 추가하세요. - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. 새 이름으로 새 테이블 스키마 (기존 테이블의 속성과 정확히 일치)를 추가합니다. - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. `astro db push --remote` 명령을 사용하여 [원격 데이터베이스로 푸시](#테이블-스키마-푸시)합니다. 그러면 새 테이블이 추가되고 이전 테이블은 더 이상 사용되지 않는 것으로 표시됩니다. -4. 이전 테이블 대신 새 테이블을 사용하도록 로컬 프로젝트 코드를 업데이트하세요. 데이터를 새 테이블로 마이그레이션해야 할 수도 있습니다. -5. 이전 테이블이 프로젝트에서 더 이상 사용되지 않는다고 확신하면 `config.ts` 파일에서 스키마를 제거할 수 있습니다. - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. `astro db push --remote` 명령을 사용하여 원격 데이터베이스로 다시 푸시합니다. 이전 테이블은 삭제되고 이름이 변경된 새 테이블만 남습니다. - - -### 테이블 데이터 푸시 - -시드 또는 데이터 마이그레이션을 위해 원격 데이터베이스에 데이터를 푸시해야 할 수도 있습니다. 타입 안정성을 갖춘 쿼리를 작성하려면 `astro:db` 모듈을 사용하여 `.ts` 파일을 작성할 수 있습니다. 그런 다음 `astro db execute --remote` 명령을 사용하여 원격 데이터베이스에 대해 파일을 실행합니다. - -다음 Comments는 `astro db execute db/seed.ts --remote` 명령을 사용하여 시드할 수 있습니다. - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!' }, - ]) -} -``` - - - -전체 명령 목록은 [CLI 참조](/ko/guides/integrations-guide/db/#astro-db-cli-참조)를 확인하세요. - - - -## Astro DB 통합 구축 - -[Astro 통합](/ko/reference/integrations-reference/)은 추가 Astro DB 테이블 및 시드 데이터를 사용하여 사용자 프로젝트를 확장할 수 있습니다. - -추가 Astro DB 구성 및 시드 파일을 등록하려면 `astro:db:setup` 후크에서 `extendDb()` 메서드를 사용하세요. -`defineDbIntegration()` 도우미는 `astro:db:setup` 후크에 대한 TypeScript 지원 및 자동 완성 기능을 제공합니다. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // 기타 통합 후크... - }, - }); -} -``` - -통합 [config](#데이터베이스-정의) 및 [seed](#개발-모드에서-데이터베이스-시드) 파일은 해당 사용자 정의 파일과 동일한 형식을 따릅니다. - -### 타입 안정성을 갖춘 통합 작업 - -통합 작업을 하는 동안, Astro에서 생성된 (`astro:db`에서 내보낸) 테이블 타입의 이점을 활용하지 못할 수도 있습니다. -완전한 타입 안정성을 위해 `asDrizzleTable()` 유틸리티를 사용하여 데이터베이스 작업에 사용할 수 있는 테이블 참조 객체를 생성하세요. - -예를 들어, 다음 `Pets` 데이터베이스 테이블을 설정하는 통합이 있다고 가정해 보겠습니다. - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -시드 파일은 `Pets`를 가져오고 `asDrizzleTable()`을 사용하여 타입 검사를 통해 테이블에 행을 삽입할 수 있습니다. - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -`asDrizzleTable('Pets', Pets)`에 의해 반환된 값은 `import { Pets } from 'astro:db'`와 동일하지만, Astro의 타입 생성을 실행할 수 없는 경우에도 사용할 수 있습니다. -데이터베이스에 쿼리하거나 삽입해야 하는 모든 통합 코드에서 이를 사용할 수 있습니다. - - - - -## Astro Studio에서 Turso로 마이그레이션 - - - -1. [Studio 대시보드](https://studio.astro.build/)에서 마이그레이션하려는 프로젝트로 이동합니다. settings 탭에서 "Export Database" 버튼을 사용해 데이터베이스 덤프를 다운로드합니다. -2. 공식 지침에 따라 [Turso CLI를 설치](https://docs.turso.tech/cli/installation)하고, Turso 계정의 [가입 또는 로그인](https://docs.turso.tech/cli/authentication)을 진행합니다. -3. `turso db create` 명령을 사용하여 Turso에서 새 데이터베이스를 생성합니다. - ```sh - turso db create [database-name] - ``` -4. Turso CLI를 사용하여 데이터베이스 URL을 가져와서 환경 변수 `ASTRO_DB_REMOTE_URL`로 사용합니다. - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. 데이터베이스에 액세스할 수 있는 토큰을 생성하고 환경 변수 `ASTRO_DB_APP_TOKEN`으로 사용합니다. - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. DB 스키마와 메타데이터를 새 Turso 데이터베이스로 푸시하세요. - ```sh - astro db push --remote - ``` -7. 1단계의 데이터베이스 덤프를 새 Turso DB로 가져옵니다. - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. 프로젝트가 새 데이터베이스에 연결되었음을 확인했으면 Astro Studio에서 프로젝트를 안전하게 삭제할 수 있습니다. - - diff --git a/src/content/docs/ko/guides/integrations-guide/db.mdx b/src/content/docs/ko/guides/integrations-guide/db.mdx index 232276e146b41..6ba20f81d9cec 100644 --- a/src/content/docs/ko/guides/integrations-guide/db.mdx +++ b/src/content/docs/ko/guides/integrations-guide/db.mdx @@ -1,393 +1,11 @@ --- -type: integration title: '@astrojs/db' description: Astro 프로젝트에서 @astrojs/db 통합을 사용하는 방법을 알아보세요. -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other i18nReady: true --- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -Astro DB는 Astro 생태계를 위해 설계된 완전 관리형 SQL 데이터베이스입니다. Astro에서 로컬로 개발하고 모든 [libSQL 호환 데이터베이스](/ko/guides/astro-db/)에 배포하세요. - -Astro DB를 사용하면 콘텐츠를 관계형 데이터베이스로 쿼리하고 모델링할 수 있는 강력하고 타입 안정성을 갖춘 로컬에서 동작하는 도구를 갖게 됩니다. - -전체 사용법과 예시는 [Astro DB 가이드](/ko/guides/astro-db/)를 참조하세요. - -## 설치 - -Astro에는 공식 통합 설정을 자동화하는 `astro add` 명령이 포함되어 있습니다. 원하는 경우 대신 [통합을 수동으로 설치](#수동-설치)할 수 있습니다. - -새 터미널 창에서 다음 명령 중 하나를 실행합니다. - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### 수동 설치 - -처음부터 직접 설정하려면 `astro add`를 건너뛰고 다음 지침에 따라 Astro DB를 직접 설치하세요. - -##### 1. 패키지 관리자를 통해 npm에서 통합 설치 - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. `astro.config.mjs` 파일에 통합 추가 - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. 데이터베이스 구성 - -프로젝트 루트에 `db/config.ts` 파일을 생성합니다. 이 파일은 Astro가 자동으로 로드하여 데이터베이스 테이블을 구성하는 데 사용되는 특수 파일입니다. - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## 구성 - -### `mode` - -

- -**타입:** `'node' | 'web'`
-**기본값:** `'node'`
- -

- -프로덕션 환경에서 데이터베이스에 연결할 때 사용할 드라이버를 구성합니다. - -기본적으로 Astro DB는 프로덕션 배포에 Node.js 기반 libSQL 드라이버를 사용합니다. Node.js 런타임을 사용하는 대부분의 Astro 호스팅 또는 자체 호스팅 웹사이트에는 `node` 드라이버 모드로 충분합니다. 이를 통해 `memory:`, `file:`, `ws:`, `wss:`, `libsql`, `http`, `https` 등 여러 프로토콜을 통해 데이터베이스에 연결할 수 있으며, [임베디드 레플리카](/ko/guides/astro-db/#syncurl)와 같은 고급 기능도 사용할 수 있습니다. - -Cloudflare Workers나 Deno와 같은 Node.js가 아닌 런타임의 서버리스 환경에 배포할 경우, 웹 기반 libSQL 드라이버를 사용할 수 있습니다. `web` 모드를 사용하여 배포할 경우, `libsql`, `http`, `https`를 통해 웹 기반 연결을 설정할 수 있습니다. - -Node.js 환경이 아닌 경우 웹 libSQL 드라이버 모드를 사용하려면 어댑터 구성에서 `mode` 속성을 설정해야 합니다. - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## 테이블 구성 참조 - -### `columns` - -

- -**타입:** `ColumnsConfig` -

- -테이블 열은 `columns` 객체를 사용하여 구성됩니다. - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -열은 `column` 유틸리티를 사용하여 구성됩니다. `column`은 다음 타입을 지원합니다: - -- **`column.text(...)`** - 일반 또는 서식 있는 텍스트 콘텐츠 저장 -- **`column.number(...)`** - 정수 및 부동 소수점 값 저장 -- **`column.boolean(...)`** - 참/거짓 값 저장 -- **`column.date(...)`** - 데이터 저장을 위해 ISO 문자열로 구문 분석된 `Date` 객체를 저장 -- **`column.json(...)`** - 데이터 저장을 위해 문자열로 구문 분석된 임의의 JSON Blob을 저장 - -모든 열에는 몇 가지 공유 구성 값이 있습니다. - -- `primaryKey` - `number` 또는 `text` 열을 고유 식별자로 설정합니다. -- `optional` - Astro DB는 기본적으로 모든 열에 `NOT NULL`을 사용합니다. null 값을 허용하려면 `optional`을 `true`로 설정하세요. -- `default` - 새로 삽입된 항목의 기본값을 설정합니다. 이는 에 대해 정적 값이나 타임스탬프와 같이 생성된 값을 나타내는 `sql` 문자열을 허용합니다. -- `unique` - 열을 고유한 것으로 표시합니다. 이렇게 하면 테이블의 항목 전체에서 값이 중복되는 것을 방지할 수 있습니다. -- `references` - 각 열과 관련된 테이블을 참조합니다. 이는 외래 키 제약 조건을 설정합니다. 즉, 각 열 값은 참조된 테이블에서 일치하는 값을 가져야 합니다. - -`text` 열은 문자열 리터럴 목록을 선택적으로 정의하여 타입 생성을 위한 열거형의 역할을 수행할 수 있습니다. 그러나 **런타임 유효성 검사는 수행되지 않습니다.** 값 제거, 추가 및 변경은 프로젝트 코드에서 처리해야 합니다. - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// 테이블을 정의합니다. -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// 결과 타입을 정의합니다. -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**타입:** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -테이블 인덱스는 특정 열 또는 열 조합에 대한 조회 속도를 향상시키는 데 사용됩니다. `indexes` 속성은 인덱스를 생성할 열을 지정하는 구성 객체의 배열을 값으로 전달받습니다. - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -그러면 `authorId` 및 `published` 열에 `Comment_authorId_published_idx`라는 이름의 고유 인덱스가 생성됩니다. - -각 인덱스에 대해 다음 구성 옵션을 사용할 수 있습니다. - -- `on` - 인덱싱할 단일 열 또는 열 이름 배열입니다. -- `unique` (선택 사항) - 인덱스가 생성된 열 전체에 고유한 값을 적용하려면 `true`로 설정합니다. -- `name` (선택 사항) - 고유 인덱스의 사용자 정의 이름입니다. 이는 색인화되는 테이블 및 열 이름을 기반으로 Astro에서 생성된 이름을 재정의합니다 (예: `Comment_authorId_published_idx`). 사용자 정의 이름은 전역적이므로 인덱스 이름이 테이블 간에 충돌하지 않는지 확인하세요. - -### `foreignKeys` - -

- -**타입:** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys`는 여러 테이블 열을 연결하기 위한 고급 API입니다. 단일 열만 참조해야 하는 경우 [열 `references` 속성](#columns)을 사용하세요. +:::caution[Deprecated] +The Astro DB integration has been deprecated in Astro v7.0 and is no longer maintained. +If you were using this integration in your project, we recommend migrating to a third-party library for database functionality. See the [Astro v7.0 migration guide](/ko/guides/upgrade-to/v7/#removed-astrojsdb) for more details and recommendations on how to update your project. ::: - -외래 키는 두 테이블 간 관계를 설정하는 데 사용됩니다. `foreignKeys` 속성은 테이블 간 하나 이상의 열을 연결할 수 있는 구성 객체의 배열을 허용합니다. - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -각 외래 키 구성 객체는 다음 속성을 허용합니다. - -- `columns` - 참조된 테이블과 관련된 단일 열 또는 열 이름의 배열입니다. -- `references` - 참조된 테이블에서 단일 열 또는 열 배열을 반환하는 함수입니다. - -## Astro DB CLI 참조 - -Astro DB에는 로컬 및 libSQL 호환 데이터베이스와 상호 작용하는 CLI 명령 세트가 포함되어 있습니다. - -이러한 명령은 GitHub CI 액션을 사용할 때 자동으로 호출되며 `astro db` CLI를 사용하여 수동으로 호출할 수 있습니다. - -### `astro db push` - -**플래그:** - -- `--db-app-token ` `ASTRO_DB_APP_TOKEN` 대신 원격 데이터베이스 앱 토큰을 직접 제공합니다. -- `--dry-run` 생성된 SQL 문을 적용하지 않고 출력합니다. -- `--force-reset` 주요 스키마 변경이 필요한 경우 모든 프로덕션 데이터를 재설정합니다. -- `--remote` 로컬 데이터베이스 파일 대신 원격 데이터베이스에 푸시합니다. `ASTRO_DB_REMOTE_URL` 환경 변수를 설정해야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -데이터베이스 구성 변경 사항을 프로젝트 데이터베이스에 안전하게 푸시합니다. 그러면 데이터 손실 위험이 있는지 확인하고 권장되는 마이그레이션 단계를 안내합니다. `--remote`를 사용하여 원격 데이터베이스에 변경 사항을 적용하세요. 주요 스키마 변경을 수행해야 하는 경우 `--force-reset`를 사용하여 모든 프로덕션 데이터를 재설정하세요. - -### `astro db verify` - -**플래그:** - -- `--db-app-token ` `ASTRO_DB_APP_TOKEN` 대신 원격 데이터베이스 앱 토큰을 직접 제공합니다. -- `--json` `verify`에서 기계가 읽을 수 있는 JSON 결과를 출력합니다. -- `--remote` 로컬 데이터베이스 파일 대신 원격 데이터베이스와 비교합니다. `ASTRO_DB_REMOTE_URL` 환경 변수가 설정되어 있어야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -로컬 스키마를 원격 데이터베이스와 비교하여 로컬 및 원격 데이터베이스 구성 간의 차이점을 확인합니다. 이 명령은 `astro db push`에 의해 자동으로 실행됩니다. - -`verify`는 로컬 `db/config.ts` 파일을 원격 데이터베이스와 비교하고 변경 사항이 감지되면 경고합니다. 변경 사항이 필요하거나 안전하지 않은 경우 0이 아닌 코드로 종료되므로 CI에 유용합니다. - -### `astro db execute ` - -**플래그:** - -- `--db-app-token ` `ASTRO_DB_APP_TOKEN` 대신 원격 데이터베이스 앱 토큰을 직접 제공합니다. -- `--remote` libSQL 호환 데이터베이스에 대해 실행합니다. 로컬 데이터베이스 파일에 대해서는 실행을 생략합니다. `ASTRO_DB_REMOTE_URL` 환경 변수가 설정되어 있어야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -데이터베이스를 읽거나 쓰려면 `.ts` 또는 `.js` 파일을 실행하세요. 이는 파일 경로를 인수로 받아들이고 `astro:db` 모듈을 사용하여 타입 안정성을 갖춘 쿼리를 작성할 수 있도록 지원합니다. libSQL 호환 데이터베이스에 대해 실행하려면 `--remote` 플래그를 사용하고, 로컬 데이터베이스 파일에 대해 실행하려면 플래그를 생략하세요. [개발 데이터를 시드](/ko/guides/astro-db/#개발-모드에서-데이터베이스-시드)하는 방법에 대한 예시 파일을 참조하세요. - -### `astro db shell --query ` - -**플래그:** - -- `--query` 실행할 원시 SQL 쿼리입니다. -- `--remote` libSQL 호환 데이터베이스에 대해 실행합니다. 로컬 데이터베이스 파일에 대해서는 실행을 생략합니다. `ASTRO_DB_REMOTE_URL` 환경 변수가 설정되어 있어야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -데이터베이스에 대해 원시 SQL 쿼리를 실행합니다. - -다음 예시는 원격 데이터베이스의 `Comment` 테이블에서 모든 행을 선택합니다. - -```sh -npx astro db shell --query "SELECT * FROM Comment;" --remote -``` - -## Astro DB 유틸리티 참조 - -다음 유틸리티는 `astro:db` 모듈에서 가져옵니다: - -```ts -import { - isDbError, - getDbError -} from "astro:db"; -``` - -### `isDbError()` - -

- -**타입:** `(err: unknown) => boolean`
- -

- -오류가 libSQL 데이터베이스 예외인지 확인합니다. 여기에는 참조 사용 시 외래 키 제약 조건 오류가 포함되거나 데이터 삽입 시 필드 누락이 포함될 수 있습니다. `isDbError()`를 try / catch 블록과 결합하여 애플리케이션의 데이터베이스 오류를 처리할 수 있습니다. - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`Cannot insert comment with id ${id}\n\n${e.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` - -### `getDbError()` - -

- -**타입:** `(err: unknown) => LibsqlError | undefined`
- -

- -오류의 원인을 탐색하여 기저에 있는 libSQL 데이터베이스 예외를 찾습니다. 이 함수는 `LibsqlError`를 반환하거나, 오류가 libSQL에서 발생한 것이 아니면 `undefined`를 반환합니다. 이는 다른 오류(예: `DrizzleQueryError`)가 데이터베이스 오류를 감싸고 있을 때 유용합니다. - -다음 예시는 발생한 예외에서 데이터베이스 오류를 추출하고 응답에 오류 코드와 메시지를 반환합니다. - -```ts title="src/pages/api/comment/[id].ts" "getDbError" -import { getDbError } from 'astro:db'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - const dbError = getDbError(e); - if (dbError) { - return new Response(`Database error: ${dbError.code}\n\n${dbError.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` diff --git a/src/content/docs/ko/reference/cli-reference.mdx b/src/content/docs/ko/reference/cli-reference.mdx index eee22f90d8b9f..887919ac9c594 100644 --- a/src/content/docs/ko/reference/cli-reference.mdx +++ b/src/content/docs/ko/reference/cli-reference.mdx @@ -266,7 +266,6 @@ check 명령을 실행할 다른 루트 디렉터리를 지정합니다. 기본 모든 Astro 모듈에 대한 TypeScript 타입을 생성합니다. 이는 타입 추론을 위한 [`.astro/types.d.ts` 파일](/ko/guides/typescript/#설정)을 설정하고 생성된 타입에 의존하는 기능에 대한 모듈을 정의합니다. - `astro:content` [콘텐츠 컬렉션 API](/ko/guides/content-collections/)를 위한 모듈 -- `astro:db` [Astro DB](/ko/guides/astro-db/)를 위한 모듈 - [실험적 Astro Env](/ko/guides/environment-variables/)를 위한 `astro:env` 모듈 - [Astro Actions](/ko/guides/actions/)를 위한 `astro:actions` 모듈 diff --git a/src/content/docs/zh-cn/guides/astro-db.mdx b/src/content/docs/zh-cn/guides/astro-db.mdx deleted file mode 100644 index 8855f54d4af60..0000000000000 --- a/src/content/docs/zh-cn/guides/astro-db.mdx +++ /dev/null @@ -1,787 +0,0 @@ ---- -title: 'Astro DB' -description: 了解如何使用 Astro DB——一个专门为 Astro 设计的全托管 SQL 数据库。 -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -Astro DB 是一款专为 Astro 设计的全托管 SQL 数据库。在 Astro 中进行本地开发并部署到任何与 libSQL 兼容的数据库。 - -Astro DB 是一种配置、开发和查询数据的完整解决方案。每当你运行`astro dev`时,都会在`.astro/content.db`中创建一个本地数据库来管理数据,而无需 Docker 或网络连接。 - -## 安装 - -使用内置的 `astro add` 命令安装 [`@astrojs/db` 集成](/zh-cn/guides/integrations-guide/db/): - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## 定义你的数据库 - -使用 `astro add` 命令安装 `@astrojs/db` 将自动在你的项目中创建一个 `db/config.ts` 文件,你可以在其中定义你的数据库表: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### 表 - -Astro DB 中的数据是通过 SQL 表存储的。表将你的数据结构化为行和列,其中列强制每行值的类型。 - -通过提供现有 libSQL 数据库中的数据结构或将在新数据库中收集的数据,在 `db/config.ts` 文件中定义表。这将允许 Astro 为你的项目生成一个 TypeScript 接口来查询该表。这意味着当你访问数据时,将获得完整的 TypeScript 支持,包括属性自动完成和类型检查。 - -要配置数据库表,应从 `astro:db` 导入并使用 `defineTable()` 和 `column` 工具。然后,为表定义一个名称(区分大小写)以及每列的数据类型。 - -这个例子配置了一个 `Comment` 表,它有 `author` 和 `body` 的必需文本列。然后,通过 `defineDb()` 导出使其在你的项目中可用。 - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -查看 [表配置参考](/zh-cn/guides/integrations-guide/db/#表配置参考) 以获取完整的表选项参考。 - -### 列 - -Astro DB 支持以下列类型: - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // 文本字符串。 - author: column.text(), - // 整数值。 - likes: column.number(), - // 布尔值。 - flagged: column.boolean(), - // 作为 JavaScript Date 对象查询的日期/时间值。 - published: column.date(), - // 未经类型化的 JSON 对象。 - metadata: column.json(), - } -}); -``` - -查看[表的列参考](/zh-cn/guides/integrations-guide/db/#表配置参考)以获取更多细节。 - -### 表引用 - -表之间的关系是数据库设计中的常见架构。例如,一个 `Blog` 表可能与 `Comment`、`Author` 和 `Category` 等其他几个表密切相关。 - -你可以使用**引用列**定义来这些表之间的关系并将它们保存到你的数据库中。要建立关系,你需要: - -- 在被引用的表上有一个**标识符列**。这通常是带有 `primaryKey` 属性的 `id` 列。 -- 在基础表上有一个用于**存储被引用 `id`** 的列。这将使用 `references` 属性来建立关系。 - -这个例子显示了一个 `Comment` 表的 `authorId` 列引用了 `Author` 表的 `id` 列。 - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## 为你的开发数据库填充数据 - -在开发过程中,Astro 将使用你的 DB 配置并根据你的架构生成本地类型。这些内容将在每次启动开发服务器时从你的 seed 文件重新生成,并允许你使用类型安全和自动补全来查询和处理你的数据样例。 - -你将无法在开发过程中访问生产数据,除非你在开发过程中 [连接到远程数据库](#连接到远程数据库)。这样可以保护你的数据,同时允许你使用类型安全的工作数据库进行测试和开发。 - -要为你的 Astro 项目填充开发数据进行测试和调试,你需要创建一个 `db/seed.ts` 文件。导入 `db` 对象和 `astro:db` 中定义的表。`insert`一些初始数据到每一个表中。这些开发数据应该与数据库模式和生产数据的结构相匹配。 - -以下例子为 `Comment` 表和 `Author` 表定义了两行开发数据: - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!'}, - ]) -} -``` - -你的开发服务器将在此文件更改时自动重启你的数据库,并每次重新生成类型并从 `seed.ts` 填充新的开发数据。 - -## 连接一个 libSQL 数据库用于生产 - -Astro DB 可以连接到任何本地 libSQL 数据库或任何暴露 libSQL 远程协议的托管或自托管服务器。 - -要连接 Astro DB 到 libSQL 数据库,设置以下从你的数据库提供商获取的环境变量: - -- `ASTRO_DB_REMOTE_URL`:连接到本地或远程 libSQL DB 的位置的连接 URL。这可能包括 [URL 配置选项](#远程-url-配置选项) 如 sync 和 encryption 作为参数。 -- `ASTRO_DB_APP_TOKEN`:你的 libSQL 服务器的认证 token。这对远程数据库是必须的,对 [本地 DB 如 文件或内存](#url-scheme-和-host) 数据库不是必须的。 - -根据你的服务,你可能会访问到一个 CLI 或 web UI 来获取这些值。以下部分将演示连接到 Turso 并设置这些值,但你也可以使用任何提供商。 - -### 开始使用 Turso - -Turso 是 [libSQL](https://github.com/tursodatabase/libsql) 背后的公司,libSQL 是 Astro DB 的底层数据库。他们提供了一个完全托管的 libSQL 数据库平台,并与 Astro 完全兼容。 - -以下步骤将引导你完成安装 Turso CLI、登录(或注册)、创建一个新数据库、获取所需的认证环境变量,并将模式推送到远程数据库的过程。 - - - -1. 安装 [Turso CLI](https://docs.turso.tech/cli/installation)。 - -2. [登录或注册](https://docs.turso.tech/cli/authentication) Turso。 - -3. 创建一个新数据库。在这个例子中,数据库名称为 `andromeda`。 - - ```sh "andromeda" - turso db create andromeda - ``` - -4. 运行 `show` 命令查看新创建数据库的信息: - - ```sh "andromeda" - turso db show andromeda - ``` - - 复制 `URL` 值并将其设置为 `ASTRO_DB_REMOTE_URL` 的值。 - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. 创建一个新 token 认证请求到数据库: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - 复制命令的输出并将其设置为 `ASTRO_DB_APP_TOKEN` 的值。 - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. 将你的 DB schema 和 metadata 推送到新的 Turso 数据库。 - - ```sh - astro db push --remote - ``` - -7. 恭喜,现在你已经连接了一个数据库!给自己一个奖励。 👾 - - ```sh - turso relax - ``` - - - -要探索更多 Turso 的功能,请查看 [Turso 文档](https://docs.turso.tech)。 - -### 连接到远程数据库 - -Astro DB 允许你连接到本地和远程数据库。默认情况下,Astro 使用一个本地数据库文件用于 `dev` 和 `build` 命令,每次重新创建表并插入开发 seed 数据。 - -要连接到一个托管的远程数据库,使用 `--remote` 标志。这个标志允许你访问远程数据库,允许你 [接受和持久化用户数据](#插入) 在生产环境中。 - -配置你的 build 命令使用 `--remote` 标志: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -你也可以直接在命令行中使用该标志: - -```bash -# 使用远程连接构建 -astro build --remote - -# 使用远程连接开发 -astro dev --remote -``` - -:::caution -在开发过程中使用 `--remote` 时请小心。这会连接到你的生产数据库,所有更改(插入、更新、删除)都会被持久化。 -::: - -`--remote` 标志在本地构建期间和服务器上都使用远程数据库连接。确保在本地开发环境和部署平台中都设置了必要的环境变量。此外,你可能还需要为非 Node.js 运行时(如 Cloudflare Workers 或 Deno)[配置 web 模式](/zh-cn/guides/integrations-guide/db/#mode)。 - -当你部署你的 Astro DB 项目时,确保你的部署平台的 build 命令设置为 `npm run build`(或你包管理器的等效命令)以使用在 `package.json` 中配置的 `--remote` 标志。 - -### 远程 URL 配置选项 - -`ASTRO_DB_REMOTE_URL` 环境变量配置了数据库的位置以及同步和加密等其他选项。 - -#### URL scheme 和 host - -libSQL 支持 HTTP 和 WebSockets 作为远程服务器的传输协议。它还支持使用本地文件或内存数据库。可以使用以下 URL 方案在连接 URL 中进行配置: - -- `memory:` 将使用内存数据库。在这种情况下,主机必须为空。 -- `file:` 将使用本地文件。主机是文件的路径 (`file:path/to/file.db`). -- `libsql:` 将通过 libSQL 库首选的协议使用远程服务器(这可能因版本而异)。主机是服务器的地址 (`libsql://your.server.io`). -- `http:` 通过 HTTP 使用远程服务器。`https:` 可以用来启用安全连接。主机与 `libsql:` 相同。 -- `ws:` 通过 WebSockets 使用远程服务器。`wss:` 可以用来启用安全连接。主机与 `libsql:` 相同。 - -libSQL 连接的详细信息(例如加密密钥、复制、同步间隔)可以在远程连接 URL 中作为查询参数进行配置。 - -例如,要将一个加密的本地文件设置为 libSQL 服务器的嵌入式副本,可以设置以下环境变量: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -使用数据库文件是一个高级特性,在部署时应该小心,以防止覆盖你的数据库并丢失你的生产数据。 - -此外,这种方法在无服务器部署中将无法工作,因为这些环境中没有持久化的文件系统。 -::: - -#### `encryptionKey` - -libSQL 对加密数据库有原生支持。传递这个搜索参数将使用给定的密钥启用加密: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -嵌入式副本是 libSQL 客户端的一个特性,它会在本地文件或内存中创建一个完整同步的副本,以实现超快的读取。写入发送到在 `syncUrl` 上定义的远程数据库,并与本地副本同步。 - -使用此属性传递一个单独的连接 URL 将数据库转换为另一个数据库的嵌入式副本。这应该仅与 `file:` 和 `memory:` 方案一起使用。该参数必须进行 URL 编码。 - -例如,要将一个数据库设置为 `libsql://your.server.io` 的内存嵌入式副本,可以设置连接 URL 如下: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -嵌入式副本之间同步的间隔时间,单位为秒。默认情况下,它仅在启动时和写入后同步。 - -此属性仅在设置 `syncUrl` 时使用。例如,要将内存嵌入式副本设置为每分钟同步,请设置以下环境变量: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## 查询你的数据库 - -你可以从项目中的任何 [Astro 页面](/zh-cn/basics/astro-pages/#astro-页面),[端点](/zh-cn/guides/endpoints/) 或 [action](/zh-cn/guides/actions/) 使用提供的 `db` ORM 和查询构建器来查询你的数据库。 - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB 包含一个内置的 [Drizzle ORM](https://orm.drizzle.team/) 客户端。使用该客户端无需设置或手动配置。当你运行 Astro 时,Astro DB 的 `db` 客户端会自动配置以与你的数据库(本地或远程)进行通信。它使用你明确的数据库架构定义进行类型安全的 SQL 查询,当你引用不存在的列或表时,会出现 TypeScript 错误。 - -### 查询 - -以下例子选择了 `Comment` 表的所有行。这将返回来自 `db/seed.ts` 全量的填充的开发数据数组,然后可以在你的页面模板中使用它们: - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comments

- -{ - comments.map(({ author, body }) => ( -
-

Author: {author}

-

{body}

-
- )) -} -``` - -查看 [Drizzle `select()` API 参考](https://orm.drizzle.team/docs/select) 以获取完整概述。 - -### 插入 - -要接受用户输入,如处理表单请求并将数据插入到你的远程托管数据库,需要为你的 Astro 项目配置 [按需渲染](/zh-cn/guides/on-demand-rendering/) 并为你的部署环境 [添加一个适配器](/zh-cn/guides/on-demand-rendering/#添加适配器)。 - -这个例子基于解析后表单的 POST 请求向 `Comment` 表插入一行: - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // 解析表单数据 - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // 将表单数据插入到 Comment 表中 - await db.insert(Comment).values({ author, body }); - } -} - -// 在每次请求上渲染新的评论列表 -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -你也可以使用 [Astro actions](/zh-cn/guides/actions/) 向 Astro DB 表中插入数据。以下例子使用一个 action 向 `Comment` 表中插入一行: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; -export const server = { - addComment: defineAction({ - // Actions 用 Zod 保证类型安全,不需要再 - // 在页面中检查 typeof {value} === 'string' - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // 返回更新后的评论 - return updatedComments; - }, - }), -}; -``` - - - -查看 [Drizzle `insert()` API 参考](https://orm.drizzle.team/docs/insert) 以获取完整概述。 - - - -### 删除 - -你也可以从 API 端点查询你的数据库。这个例子通过 `id` 参数删除 `Comment` 表中的一行: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - -查看 [Drizzle `delete()` API 参考](https://orm.drizzle.team/docs/delete) 以获取完整概述。 - - -### 过滤 - -要通过特定属性查询表结果,请使用 [Drizzle 的部分查询选项](https://orm.drizzle.team/docs/select#partial-select)。例如,向你的 `select()` 查询添加 [一个 `.where()` 调用](https://orm.drizzle.team/docs/select#filtering),并传递你想做的比较操作。 - -以下例子查询了 `Comment` 表中包含 "Astro DB" 短语的所有行。使用 [`like()` 操作符](https://orm.drizzle.team/docs/operators#like) 检查 `body` 中是否存在短语: - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Drizzle 辅助工具 - -所有用于构建查询的 Drizzle 辅助工具都从 `astro:db` 模块中暴露出来。这包括: - -- [过滤操作符](https://orm.drizzle.team/docs/operators) 如 `eq()` 和 `gt()` -- [聚合辅助工具](https://orm.drizzle.team/docs/select#aggregations-helpers) 如 `count()` -- 用于编写原始 SQL 查询语句的 [`sql` 辅助工具](https://orm.drizzle.team/docs/sql) - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### 关系 - -你可以使用 SQL 连接从多个表查询关联的数据。要创建一个连接查询,请使用连接操作符扩展你的 `db.select()` 语句。每个函数都接受一个要连接的表和一个条件来匹配两个表之间的行。 - -这个例子使用了 `innerJoin()` 函数将 `Comment` 的作者与他们相关的 `Author` 信息连接起来,基于 `authorId` 列。这将返回一个对象数组,每个 `Author` 和 `Comment` 行作为顶级属性: - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comments

- -{ - comments.map(({ Author, Comment }) => ( -
-

Author: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -查看 [Drizzle 连接参考](https://orm.drizzle.team/docs/joins#join-types) 以获取所有可用的连接操作符和配置选项。 - - - -### 批处理事务 - -所有远程数据库查询都作为网络请求进行。当进行大量查询,或者如果任何查询失败需要自动回滚时,你可能需要将查询批量处理为单个事务。 - -这个例子使用 `db.batch()` 方法在单个请求中填充多行: - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // 使用单个网络请求将 100 个样本数据填充到你的远程数据库中。 - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -查看 [Drizzle `db.batch()`](https://orm.drizzle.team/docs/batch-api) 文档以获取更多详细信息。 - - - -## 将更改推送到你的数据库 - -你可以将开发期间所做的更改推送到你的数据库。 - -### 推送表架构 - -你的表架构可能会随着项目的增长而变化。你可以在本地安全地测试配置更改,并在部署时推送到你的远程数据库。 - -你可以通过 CLI 使用 `astro db push --remote` 命令将本地架构更改推送到远程数据库: - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -此命令将验证你的本地更改是否可以在不丢失数据的情况下进行,并在必要时,建议如何安全地修改你的架构以解决冲突。 - -#### 推送破坏性架构更改 - -:::danger -__这将销毁你的数据库__。仅在你不需要生产数据时执行此命令。 -::: - -如果必须以与现有数据不兼容的方式更改表架构,则需要重置生产数据库。 - -要推送包含破坏性更改的表架构更新,请添加 `--force-reset` 标志以重置所有生产数据: - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### 重命名表 - -在将架构推送到远程数据库后,可以重命名表。 - -如果 **没有重要的生产数据**,则可以使用 `--force-reset` 标志 [重置你的数据库](#推送破坏性架构更改)。此标志将删除数据库中的所有表并创建新的表,以匹配当前的架构。 - -为了在保留你的生产数据的同时重命名一个表,你必须执行一系列非破坏性更改,以安全地将本地架构推送到远程数据库。 - -以下示例将表从 `Comment` 重命名为 `Feedback`: - - - -1. 在你的数据库配置文件中,为你想要重命名的表添加 `deprecated: true` 属性: - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. 添加一个新的表架构(完全匹配现有表的属性)并使用新名称: - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. 使用 `astro db push --remote`[将架构推送到远程数据库](#推送表架构) 。这将添加新表并将旧表标记为已弃用。 -4. 更新你的本地项目代码以使用新表而不是旧表。你可能还需要将数据迁移到新表。 -5. 一旦你确信旧表在你的项目中不再使用,你可以从 `config.ts` 中删除旧表的架构: - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. 再次使用 `astro db push --remote`推送到远程数据库。旧表将被删除,只留下新的、重命名的表。 - - -### 推送表数据 - -你可能需要将数据推送到远程数据库以进行填充或数据迁移。你可以编写一个 `.ts` 文件并使用 `astro:db` 模块来编写类型安全的查询。然后,使用命令 `astro db execute --remote` 对远程数据库执行该文件: - -以下评论可以使用命令 `astro db execute db/seed.ts --remote` 进行填充: - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!' }, - ]) -} -``` - - - -查看 [CLI 参考](/zh-cn/guides/integrations-guide/db/#astro-db-cli-参考) 以获取完整的命令列表。 - - - -## 构建 Astro DB 集成 - -[Astro 集成](/zh-cn/reference/integrations-reference/) 可以通过额外的 Astro DB 表和填充数据来扩展用户项目。 - -在 `astro:db:setup` 钩子中使用 `extendDb()` 方法注册额外的 Astro DB 配置和填充文件。 -`defineDbIntegration()` 辅助函数为 `astro:db:setup` 钩子提供 TypeScript 支持和自动补全。 - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // 其他集成钩子... - }, - }); -} -``` - -集成的 [配置](#定义你的数据库) 和 [填充](#为你的开发数据库填充数据) 文件遵循与其用户定义的等效项相同的格式。 - -### 在集成中进行类型安全操作 - -在进行集成工作时,你可能无法从 `astro:db` 导出的 Astro 生成的表类型中获益。 -为了完全的类型安全,使用 `asDrizzleTable()` 辅助工具创建一个可以用于数据库操作的表引用对象。 - -例如,给定一个集成设置以下 `Pets` 数据库表: - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -填充文件可以导入 `Pets` 并使用 `asDrizzleTable()` 向你的表插入具有类型检查的行: - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -`asDrizzleTable('Pets', Pets)` 返回的值等同于 `import { Pets } from 'astro:db'`,但即使 Astro 的类型生成无法运行时也可用。 -你可以在任何需要查询或插入数据库的集成代码中使用它。 - - -## 从 Astro Studio 迁移到 Turso - - - -1. 在 [Studio 仪表板](https://studio.astro.build/) 中,导航到你要迁移的项目。在设置选项卡中,使用 “Export Database(导出数据库)” 按钮下载数据库的转储。 -2. 按照官方说明 [安装 Turso CLI](https://docs.turso.tech/cli/installation) 并 [注册或登录](https://docs.turso.tech/cli/authentication) 你的 Turso 帐户。 -3. 使用 `turso db create` 命令在 Turso 上创建一个新数据库。 - ```sh - turso db create [database-name] - ``` -4. 使用 Turso CLI 获取数据库 URL,并将其配置为环境变量 `ASTRO_DB_REMOTE_URL`。 - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. 创建一个令牌来访问你的数据库,并将其配置为环境变量 `ASTRO_DB_APP_TOKEN`。 - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. 将你的 DB 架构和元数据推送到新的 Turso 数据库。 - ```sh - astro db push --remote - ``` -7. 将步骤 1 中的数据库转储导入到新的 Turso DB 中。 - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. 确认你的项目连接到新数据库后,你就可以安全地从 Astro Studio 中删除该项目了。 - - diff --git a/src/content/docs/zh-cn/guides/integrations-guide/db.mdx b/src/content/docs/zh-cn/guides/integrations-guide/db.mdx index ab3d06b95e765..e2add39bb7d46 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/db.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/db.mdx @@ -1,331 +1,11 @@ --- -type: integration title: '@astrojs/db' description: 了解如何在你的 Astro 项目中使用 @astrojs/db 集成。 -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other i18nReady: true --- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -Astro DB 是一个为 Astro 生态设计的全托管 SQL 数据库:你可以在本地使用 Astro 进行开发,并部署到任何 [libSQL 兼容的数据库](/zh-cn/guides/astro-db/)。 - -有了 Astro DB,你就拥有了一个强大的、本地的、类型安全的工具,可以像关系数据库查询和构建内容。 - -查看 [Astro DB 指南](/zh-cn/guides/astro-db/) 以获取完整的使用方法和示例。 - -## 安装 - -Astro 包含了一个 `astro add` 命令,用于自动设置官方集成。如果你愿意,你也可以选择[手动安装集成](#手动安装)。 - -在新的终端窗口中运行以下之一的命令。 - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### 手动安装 - -如果你更喜欢自己从头开始设置,可以跳过 `astro add`,并按照以下说明自行安装 Astro DB。 - -##### 1. 通过包管理器从 npm 安装集成 - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. 将集成添加到 `astro.config.mjs` - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. 配置你的数据库 - -在项目的根目录下创建一个 `db/config.ts` 文件。这是一个特殊的文件,Astro 会自动加载并用它来配置你的数据库表。 - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## 配置 - -### `mode` - -

- -**类型:** `'node' | 'web'`
-**默认值:** `'node'`
- -

- -配置用于在生产环境中连接到数据库的驱动程序。 - -默认情况下,Astro DB 在生产部署中使用基于 Node.js 的 libSQL 驱动程序。`node` 驱动程序模式足以满足大多数使用 Node.js 运行时的 Astro 托管或自托管网站的需求。这使你能够通过 `memory:`、`file:`、`ws:`、`wss:`、`libsql`、`http` 和 `https` 等多种协议连接到你的数据库,并且支持[嵌入式副本](/zh-cn/guides/astro-db/#syncurl)等高级功能。 - -当在非 Node.js 运行时(例如 Cloudflare Workers 或 Deno)的无服务器环境中部署时,可以使用基于 Web 的 libSQL 驱动程序。使用 `web` 模式部署时,你将能够通过 `libsql`、`http` 或 `https` 建立基于 Web 的连接。 - -要在非 Node.js 环境中使用 web libSQL 驱动模式,请在适配器的配置中设置 `mode` 属性: - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## 表配置参考 - -### `columns` -

- -**类型:** `ColumnsConfig` -

-表的列是使用 `columns` 对象配置: - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -列是使用 `column` 辅助工具进行配置的。`column` 支持以下类型: - -- **`column.text(...)`** - 存储纯文本或富文本内容 -- **`column.number(...)`** - 存储整数和浮点值 -- **`column.boolean(...)`** - 存储 true / false 值 -- **`column.date(...)`** - 存储 `Date` 对象,解析为 ISO 字符串用于数据存储 -- **`column.json(...)`** - 存储任意 JSON blobs,解析为字符串化的 JSON 用于数据存储 - -所有列都有一些共享的配置值: - -- `primaryKey` - 将 `number` 或 `text` 列设置为唯一标识符。 -- `optional` - Astro DB 默认对所有列使用 `NOT NULL`。将 `optional` 设置为 `true` 以允许 null 值。 -- `default` - 设置新插入条目的默认值。这可以接受静态值或生成值(如时间戳)的 `sql` 字符串。 -- `unique` - 将列标记为唯一。这将防止表中条目的值重复。 -- `references` - 通过列引用相关表。这会建立一个外键约束,意味着每个列值必须在引用的表中有一个匹配的值。 - -`text` 列可以选择性地定义字符串字面量列表以用作生成枚举类型。但是,**这不会在运行时执行任何校验**。删除、添加和更改这些值都应该由你的项目代码来处理。 - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// 表定义 -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// 生成的类型定义 -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**类型:** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -表索引用于提高在特定列或列组合上的查找速度。`indexes` 属性接受一个配置对象数组,用于指定要索引的列: - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -这将在 `authorId` 和 `published` 列上生成一个名为 `Comment_authorId_published_idx` 的唯一索引。 - -每个索引都有以下配置选项: - -- `on` - 要索引的单个列或列名数组。 -- `unique` (可选) - 设置为 `true` 以在索引列上强制唯一值。 -- `name` (可选) - 为唯一索引指定一个自定义名称。这将覆盖 Astro 根据被索引的表和列名生成的名称(例如 `Comment_authorId_published_idx`)。自定义名称是全局的,因此请确保索引名称在不同的表之间不会冲突。 - -### `foreignKeys` - -

- -**类型:** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys` 是一个用于关联多个表列的高级 API。如果你只需要引用一个单独的列,试试使用[列 `references` 属性。](#columns) +:::caution[Deprecated] +The Astro DB integration has been deprecated in Astro v7.0 and is no longer maintained. +If you were using this integration in your project, we recommend migrating to a third-party library for database functionality. See the [Astro v7.0 migration guide](/zh-cn/guides/upgrade-to/v7/#removed-astrojsdb) for more details and recommendations on how to update your project. ::: - -外键用于建立两个表之间的关系。`foreignKeys` 属性接受一个配置对象数组,可以在表之间关联一个或多个列: - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -每个外键配置对象接受以下属性: - -- `columns`: - 要与引用表关联的单个列名或者列名数组。 -- `references`: - 返回引用表的单列或者列数组的函数。 - -## Astro DB CLI 参考 - -Astro DB 包含一组 CLI 命令,用于与你的本地和 libSQL 兼容数据库进行交互。 - -当使用 GitHub CI 流水线时,这些命令会被自动调用,你也可以使用 `astro db` CLI 手动调用它们。 - -### `astro db push` - -**标志:** - -- `--force-reset` 如果需要进行破坏性的模式更改,则重置所有生产数据。 - -安全地将数据库配置更改推送到你的项目数据库。这将检查任何数据丢失的风险,并指导你进行任何推荐的迁移步骤。如果必须进行破坏性的模式更改,使用 `--force-reset` 标志重置所有生产数据。 - -### `astro db verify` - -检查你的本地和远程数据库配置之间的任何差异。这是由 `astro db push` 自动运行的。`verify` 将比较你的本地 `db/config.ts` 文件与远程数据库,并在检测到更改时发出警告。 - -### `astro db execute ` - -**标志:** - -- `--remote` 在你的 libSQL 兼容数据库上运行。省略则在你的开发服务器上运行。 - -执行一个 `.ts` 或 `.js` 文件以读取或写入你的数据库。这接受一个文件路径作为参数,并支持使用 `astro:db` 模块编写类型安全的查询。使用 `--remote` 标志在你的 libSQL 兼容数据库上运行,或省略该标志在你的开发服务器上运行。参见如何[填充开发数据](/zh-cn/guides/astro-db/#为你的开发数据库填充数据)以获取一个示例文件。 - -### `astro db shell --query ` - -**标志:** - -- `--query` 要执行的原始 SQL 查询语句。 -- `--remote` 在你的 libSQL 兼容数据库上运行。省略则在你的开发服务器上运行。 - -对你的数据库执行原始 SQL 查询。使用 `--remote` 标志在你的 libSQL 兼容数据库上运行,或省略该标志在你的开发服务器上运行。 - -## Astro DB 工具函数参考 - -### `isDbError()` - - -

- -**类型:** `(err: unknown) => boolean`
- -

- -`isDbError()` 函数用于检查一个错误是否是 libSQL 数据库异常。这可能包括在使用引用时的外键约束错误,或在插入数据时缺少字段。你可以将 `isDbError()` 与 try / catch 块结合使用,来处理应用程序中的数据库错误: - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = async (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`无法插入 id 为 ${ctx.params.id} 的评论\n\n${e.message}`, { status: 400 }); - } - return new Response('发生了意外错误', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; diff --git a/src/content/docs/zh-cn/reference/cli-reference.mdx b/src/content/docs/zh-cn/reference/cli-reference.mdx index 451e8d5bc5b9c..79c08efc55eb0 100644 --- a/src/content/docs/zh-cn/reference/cli-reference.mdx +++ b/src/content/docs/zh-cn/reference/cli-reference.mdx @@ -267,7 +267,6 @@ Flags 为所有 Astro 模块生成 TypeScript 类型。这会为类型推断设置一个[`.astro/types.d.ts`文件](/zh-cn/guides/typescript/#设置),并为依赖于生成类型的特性定义模块: - `astro:content` 模块用于 [内容集合 API](/zh-cn/guides/content-collections/)。 -- `astro:db` 模块用于 [Astro DB](/zh-cn/guides/astro-db/)。 - `astro:env` 模块用于 [Astro Env](/zh-cn/guides/environment-variables/)。 - `astro:actions` 模块用于 [Astro Actions](/zh-cn/guides/actions/)。