Skip to content

Commit ca32fcf

Browse files
authored
Merge pull request #591 from divyenduz/xata_tutorial
add xata tutorial
2 parents 926ce90 + b0ead48 commit ca32fcf

File tree

1 file changed

+348
-0
lines changed

1 file changed

+348
-0
lines changed
Lines changed: 348 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,348 @@
1+
---
2+
title: "Drizzle with Xata"
3+
date: "2024-12-13"
4+
svgs: ['<svg width="160" height="160" viewBox="0 0 160 160" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="9.63139" height="40.8516" rx="4.8157" transform="matrix(0.873028 0.48767 -0.497212 0.867629 43.4805 67.3037)" fill="currentColor"></rect><rect width="9.63139" height="40.8516" rx="4.8157" transform="matrix(0.873028 0.48767 -0.497212 0.867629 76.9395 46.5342)" fill="currentColor"></rect><rect width="9.63139" height="40.8516" rx="4.8157" transform="matrix(0.873028 0.48767 -0.497212 0.867629 128.424 46.5352)" fill="currentColor"></rect><rect width="9.63139" height="40.8516" rx="4.8157" transform="matrix(0.873028 0.48767 -0.497212 0.867629 94.957 67.3037)" fill="currentColor"></rect></svg>', '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>']
5+
---
6+
7+
import Prerequisites from "@mdx/Prerequisites.astro";
8+
import Npm from '@mdx/Npm.astro';
9+
import Steps from '@mdx/Steps.astro';
10+
import Section from "@mdx/Section.astro";
11+
import Callout from '@mdx/Callout.astro';
12+
13+
This tutorial demonstrates how to use Drizzle ORM with [Xata](https://xata.io). Xata is a PostgreSQL database platform designed to help developers operate and scale databases with enhanced productivity and performance, featuring instant copy-on-write database branches, zero-downtime schema changes, data anonymization, and AI-powered performance monitoring.
14+
15+
<Prerequisites>
16+
- You should have installed Drizzle ORM and [Drizzle kit](/docs/kit-overview). You can do this by running the following command:
17+
<Npm>
18+
drizzle-orm
19+
-D drizzle-kit
20+
</Npm>
21+
- You should have installed `dotenv` package for managing environment variables. Read more about this package [here](https://www.npmjs.com/package/dotenv)
22+
<Npm>
23+
dotenv
24+
</Npm>
25+
26+
- You should have installed `postgres` package for connecting to the Postgres database. Read more about this package [here](https://www.npmjs.com/package/postgres)
27+
<Npm>
28+
postgres
29+
</Npm>
30+
31+
- You should have a Xata account and database set up. Follow the [Xata documentation](https://xata.io/documentation/getting-started) to create your account and database
32+
</Prerequisites>
33+
34+
Check [Xata documentation](https://xata.io/documentation/quickstarts/drizzle) to learn more about using Drizzle ORM with Xata.
35+
36+
## Setup Xata and Drizzle ORM
37+
38+
<Steps>
39+
#### Create a new Xata database
40+
41+
You can create a new Xata database by following these steps:
42+
43+
1. Sign up or log in to your [Xata account](https://xata.io/)
44+
2. Create a new database from the dashboard
45+
3. Choose your region and database name
46+
4. Your database will be created with a PostgreSQL endpoint
47+
48+
#### Setup connection string variable
49+
50+
Navigate to the Xata dashboard and copy the PostgreSQL connection string. You can find this on the branch overview page.
51+
52+
Add `DATABASE_URL` variable to your `.env` or `.env.local` file:
53+
54+
```plaintext copy
55+
DATABASE_URL=<YOUR_XATA_DATABASE_URL>
56+
```
57+
58+
The connection string format will be:
59+
```plaintext
60+
postgresql://postgres:<password>@<branch-id>.<region>.xata.tech/<database>?sslmode=require
61+
```
62+
63+
Example:
64+
```plaintext
65+
postgresql://postgres:[email protected]/app?sslmode=require
66+
```
67+
68+
<Callout type="info">
69+
Xata provides branch-based development, allowing you to create isolated database branches for development, staging, and production environments.
70+
</Callout>
71+
72+
#### Connect Drizzle ORM to your database
73+
74+
Create a `index.ts` file in the `src/db` directory and set up your database configuration:
75+
76+
```typescript copy filename="src/db/index.ts"
77+
import { config } from 'dotenv';
78+
import { drizzle } from 'drizzle-orm/postgres-js';
79+
import postgres from 'postgres';
80+
81+
config({ path: '.env' }); // or .env.local
82+
83+
const client = postgres(process.env.DATABASE_URL!);
84+
export const db = drizzle({ client });
85+
```
86+
87+
#### Create tables
88+
89+
Create a `schema.ts` file in the `src/db` directory and declare your tables:
90+
91+
```typescript copy filename="src/db/schema.ts"
92+
import { integer, pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core';
93+
94+
export const usersTable = pgTable('users_table', {
95+
id: serial('id').primaryKey(),
96+
name: text('name').notNull(),
97+
age: integer('age').notNull(),
98+
email: text('email').notNull().unique(),
99+
});
100+
101+
export const postsTable = pgTable('posts_table', {
102+
id: serial('id').primaryKey(),
103+
title: text('title').notNull(),
104+
content: text('content').notNull(),
105+
userId: integer('user_id')
106+
.notNull()
107+
.references(() => usersTable.id, { onDelete: 'cascade' }),
108+
createdAt: timestamp('created_at').notNull().defaultNow(),
109+
updatedAt: timestamp('updated_at')
110+
.notNull()
111+
.$onUpdate(() => new Date()),
112+
});
113+
114+
export type InsertUser = typeof usersTable.$inferInsert;
115+
export type SelectUser = typeof usersTable.$inferSelect;
116+
117+
export type InsertPost = typeof postsTable.$inferInsert;
118+
export type SelectPost = typeof postsTable.$inferSelect;
119+
```
120+
121+
#### Setup Drizzle config file
122+
123+
**Drizzle config** - a configuration file that is used by [Drizzle Kit](/docs/kit-overview) and contains all the information about your database connection, migration folder and schema files.
124+
125+
Create a `drizzle.config.ts` file in the root of your project and add the following content:
126+
127+
```typescript copy filename="drizzle.config.ts"
128+
import { config } from 'dotenv';
129+
import { defineConfig } from 'drizzle-kit';
130+
131+
config({ path: '.env' });
132+
133+
export default defineConfig({
134+
schema: './src/db/schema.ts',
135+
out: './migrations',
136+
dialect: 'postgresql',
137+
dbCredentials: {
138+
url: process.env.DATABASE_URL!,
139+
},
140+
});
141+
```
142+
143+
#### Applying changes to the database
144+
145+
You can generate migrations using `drizzle-kit generate` command and then run them using the `drizzle-kit migrate` command.
146+
147+
Generate migrations:
148+
149+
```bash copy
150+
npx drizzle-kit generate
151+
```
152+
153+
These migrations are stored in the `migrations` directory, as specified in your `drizzle.config.ts`. This directory will contain the SQL files necessary to update your database schema and a `meta` folder for storing snapshots of the schema at different migration stages.
154+
155+
Example of a generated migration:
156+
157+
```sql
158+
CREATE TABLE IF NOT EXISTS "posts_table" (
159+
"id" serial PRIMARY KEY NOT NULL,
160+
"title" text NOT NULL,
161+
"content" text NOT NULL,
162+
"user_id" integer NOT NULL,
163+
"created_at" timestamp DEFAULT now() NOT NULL,
164+
"updated_at" timestamp NOT NULL
165+
);
166+
--> statement-breakpoint
167+
CREATE TABLE IF NOT EXISTS "users_table" (
168+
"id" serial PRIMARY KEY NOT NULL,
169+
"name" text NOT NULL,
170+
"age" integer NOT NULL,
171+
"email" text NOT NULL,
172+
CONSTRAINT "users_table_email_unique" UNIQUE("email")
173+
);
174+
--> statement-breakpoint
175+
DO $$ BEGIN
176+
ALTER TABLE "posts_table" ADD CONSTRAINT "posts_table_user_id_users_table_id_fk" FOREIGN KEY ("user_id") REFERENCES "users_table"("id") ON DELETE cascade ON UPDATE no action;
177+
EXCEPTION
178+
WHEN duplicate_object THEN null;
179+
END $$;
180+
```
181+
182+
Run migrations:
183+
184+
```bash copy
185+
npx drizzle-kit migrate
186+
```
187+
188+
Learn more about [migration process](/docs/migrations).
189+
190+
Alternatively, you can push changes directly to the database using [Drizzle kit push command](/docs/kit-overview#prototyping-with-db-push):
191+
192+
```bash copy
193+
npx drizzle-kit push
194+
```
195+
196+
<Callout type="warning">Push command is good for situations where you need to quickly test new schema designs or changes in a local development environment, allowing for fast iterations without the overhead of managing migration files.</Callout>
197+
198+
<Callout type="info">
199+
**Xata Branch-Based Development**: Xata allows you to create database branches for different environments. You can use different connection strings for development, staging, and production branches, making it easy to test schema changes before deploying to production.
200+
</Callout>
201+
</Steps>
202+
203+
## Basic file structure
204+
205+
This is the basic file structure of the project. In the `src/db` directory, we have database-related files including connection in `index.ts` and schema definitions in `schema.ts`.
206+
207+
```plaintext
208+
📦 <project root>
209+
├ 📂 src
210+
│ ├ 📂 db
211+
│ │ ├ 📜 index.ts
212+
│ │ └ 📜 schema.ts
213+
├ 📂 migrations
214+
│ ├ 📂 meta
215+
│ │ ├ 📜 _journal.json
216+
│ │ └ 📜 0000_snapshot.json
217+
│ └ 📜 0000_watery_spencer_smythe.sql
218+
├ 📜 .env
219+
├ 📜 drizzle.config.ts
220+
├ 📜 package.json
221+
└ 📜 tsconfig.json
222+
```
223+
224+
## Query examples
225+
226+
For instance, we create `src/db/queries` folder and separate files for each operation: insert, select, update, delete.
227+
228+
#### Insert data
229+
230+
Read more about insert query in the [documentation](/docs/insert).
231+
232+
```typescript copy filename="src/db/queries/insert.ts" {4, 8}
233+
import { db } from '../index';
234+
import { InsertPost, InsertUser, postsTable, usersTable } from '../schema';
235+
236+
export async function createUser(data: InsertUser) {
237+
await db.insert(usersTable).values(data);
238+
}
239+
240+
export async function createPost(data: InsertPost) {
241+
await db.insert(postsTable).values(data);
242+
}
243+
```
244+
245+
#### Select data
246+
247+
Read more about select query in the [documentation](/docs/select).
248+
249+
```typescript copy filename="src/db/queries/select.ts" {5, 16, 41}
250+
import { asc, between, count, eq, getTableColumns, sql } from 'drizzle-orm';
251+
import { db } from '../index';
252+
import { SelectUser, postsTable, usersTable } from '../schema';
253+
254+
export async function getUserById(id: SelectUser['id']): Promise<
255+
Array<{
256+
id: number;
257+
name: string;
258+
age: number;
259+
email: string;
260+
}>
261+
> {
262+
return db.select().from(usersTable).where(eq(usersTable.id, id));
263+
}
264+
265+
export async function getUsersWithPostsCount(
266+
page = 1,
267+
pageSize = 5,
268+
): Promise<
269+
Array<{
270+
postsCount: number;
271+
id: number;
272+
name: string;
273+
age: number;
274+
email: string;
275+
}>
276+
> {
277+
return db
278+
.select({
279+
...getTableColumns(usersTable),
280+
postsCount: count(postsTable.id),
281+
})
282+
.from(usersTable)
283+
.leftJoin(postsTable, eq(usersTable.id, postsTable.userId))
284+
.groupBy(usersTable.id)
285+
.orderBy(asc(usersTable.id))
286+
.limit(pageSize)
287+
.offset((page - 1) * pageSize);
288+
}
289+
290+
export async function getPostsForLast24Hours(
291+
page = 1,
292+
pageSize = 5,
293+
): Promise<
294+
Array<{
295+
id: number;
296+
title: string;
297+
}>
298+
> {
299+
return db
300+
.select({
301+
id: postsTable.id,
302+
title: postsTable.title,
303+
})
304+
.from(postsTable)
305+
.where(between(postsTable.createdAt, sql`now() - interval '1 day'`, sql`now()`))
306+
.orderBy(asc(postsTable.title), asc(postsTable.id))
307+
.limit(pageSize)
308+
.offset((page - 1) * pageSize);
309+
}
310+
```
311+
312+
Alternatively, you can use [relational query syntax](/docs/rqb).
313+
314+
#### Update data
315+
316+
Read more about update query in the [documentation](/docs/update).
317+
318+
```typescript copy filename="src/db/queries/update.ts" {5}
319+
import { eq } from 'drizzle-orm';
320+
import { db } from '../index';
321+
import { SelectPost, postsTable } from '../schema';
322+
323+
export async function updatePost(id: SelectPost['id'], data: Partial<Omit<SelectPost, 'id'>>) {
324+
await db.update(postsTable).set(data).where(eq(postsTable.id, id));
325+
}
326+
```
327+
328+
#### Delete data
329+
330+
Read more about delete query in the [documentation](/docs/delete).
331+
332+
```typescript copy filename="src/db/queries/delete.ts" {5}
333+
import { eq } from 'drizzle-orm';
334+
import { db } from '../index';
335+
import { SelectUser, usersTable } from '../schema';
336+
337+
export async function deleteUser(id: SelectUser['id']) {
338+
await db.delete(usersTable).where(eq(usersTable.id, id));
339+
}
340+
```
341+
342+
## Next Steps
343+
344+
Now that you have successfully set up Drizzle ORM with Xata, you can explore more advanced features:
345+
346+
- Learn about [Drizzle relations](/docs/rqb) for complex queries
347+
- Explore [Xata's documentation](https://xata.io/documentation/)
348+
- Implement [database migrations](/docs/migrations) for production deployments

0 commit comments

Comments
 (0)