Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a sample on rds prisma migration #236

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions rds-prisma-migration/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="postgresql://test:[email protected]:4510/test"
35 changes: 35 additions & 0 deletions rds-prisma-migration/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export AWS_ACCESS_KEY_ID ?= test
export AWS_SECRET_ACCESS_KEY ?= test
export AWS_DEFAULT_REGION = us-east-1
SHELL := /bin/bash
PYTHON_BIN ?= $(shell which python3 || which python)

usage: ## Show this help
@fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//'

install: ## Install dependencies
@which localstack || pip install localstack
@which awslocal || pip install awscli-local
@test -e .venv || ($(PYTHON_BIN) -m venv .venv; source .venv/bin/activate; pip install wheel; pip install psycopg2-binary boto3)

run:
./run.sh

start:
localstack start -d

stop:
@echo
localstack stop
ready:
@echo Waiting on the LocalStack container...
@localstack wait -t 30 && echo Localstack is ready to use! || (echo Gave up waiting on LocalStack, exiting. && exit 1)

logs:
@localstack logs > logs.txt

test-ci:
make start install ready run; return_code=`echo $$?`;\
make logs; make stop; exit $$return_code;

.PHONY: usage install start run stop ready logs test-ci
144 changes: 144 additions & 0 deletions rds-prisma-migration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# Testing RDS migrations locally with Prisma & LocalStack

In this sample application, we demonstrate how you can test your RDS migrations locally using Prisma and LocalStack. Prisma is a database ORM for Node.js applications, and this sample application showcases how you can use Prisma to run migration, generate model for the client, and run a small test inserting and querying data into the database.

## Prerequisites

* LocalStack
* Docker
* Node.js & `npm`
* `make`
* [`awslocal`](https://github.com/localstack/awscli-local)

## Start your LocalStack container

Start your LocalStack container with the `LOCALSTACK_AUTH_TOKEN` specified:

```bash
LOCALSTACK_AUTH_TOKEN=... DEBUG=1 localstack start
```

## Install the dependencies

Install the dependencies required for the application:

```bash
npm install
```

You can run the following command to see if Prisma is correctly installed:

```bash
npx prisma
```

## Create a local RDS database

You can now create a local RDS database using the `awslocal` CLI:

```bash
awslocal rds create-db-cluster \
--db-cluster-identifier cluster1 \
--engine=aurora-postgresql \
--database-name test
```

**Note**: Check the port in the response, since you might have to adjust the `.env` file with the right port in the database URL.

## Run the migration

You can now run the migration using Prisma:

```bash
npx prisma migrate dev --name init
```

The following output should be displayed:

```bash
Environment variables loaded from .env
Prisma schema loaded from prisma/schema.prisma
Datasource "db": PostgreSQL database "test", schema "public" at "0.0.0.0:4510"

Applying migration `20240213041046_init`

The following migration(s) have been created and applied from new schema changes:

migrations/
└─ 20240213041046_init/
└─ migration.sql

Your database is now in sync with your schema.

✔ Generated Prisma Client (4.16.2 | library) to ./node_modules/@prisma/client in 63ms
```

## Generate models for the client

You can now generate the models for the client using Prisma:

```bash
npx generate
```

To run a small test inserting and querying data into the DB, you can run the following command:

```bash
npx ts-node main.ts
```

The following output should be displayed:

```bash
[
{
id: 1,
email: '[email protected]',
name: 'Alice',
posts: [
{
id: 1,
createdAt: 2024-02-13T04:13:39.901Z,
updatedAt: 2024-02-13T04:13:39.901Z,
title: 'Hello World',
content: null,
published: false,
authorId: 1
}
],
profile: { id: 1, bio: 'I like turtles', userId: 1 }
}
]
```

## Run a (re) migration

You can run another migration. A new schema is already created for you, and you just need to specify it while running the migration command.

```bash
npx prisma migrate dev --name init --schema=./prisma/schema-test.prisma
```

The following output should be displayed:

```bash
Environment variables loaded from .env
Prisma schema loaded from prisma/schema-test.prisma
Datasource "db": PostgreSQL database "test", schema "public" at "0.0.0.0:4510"

Applying migration `20240213041407_init`

The following migration(s) have been created and applied from new schema changes:

migrations/
└─ 20240213041407_init/
└─ migration.sql

Your database is now in sync with your schema.

✔ Generated Prisma Client (4.16.2 | library) to ./node_modules/@prisma/client in 62ms
```

## License

This code is licensed under the Apache 2.0 License.
36 changes: 36 additions & 0 deletions rds-prisma-migration/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main () {
await prisma.user.create({
data: {
name: 'Alice',
email: '[email protected]',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})

const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
Loading
Loading