Prisma

Explore how you can use Prisma, and its GraphQL support, to interact with YugabyteDB. You will quickly build a GraphQL server and then use the Prisma client to write data to and run queries on a YugabyteDB database. Also, you’ll get a taste of Prisma’s ORM functionality.

Prisma is an open source suite of database tools that simplify database workflows by easing database access, migrations, and data management. Prisma replaces traditional ORMs and can be used to build GraphQL servers, REST APIs, microservices, and more. For an overview, see Prisma Basics: Datamodel, Prisma Client & Server.

Before you begin

YugabyteDB

If YugabyteDB is installed, run the following yb-ctl create command to start a YugabyteDB 1-node cluster, setting the default transaction isolation level to serializable:

  1. ./bin/yb-ctl create --tserver_flags=ysql_pg_conf="default_transaction_isolation=serializable"

If you are new to YugabyteDB, you can be up and running with YugabyteDB in under five minutes by following the steps in Quick start. After installing YugabyteDB, make sure to follow the step mentioned above.

Prisma

To use Prisma, npm and Docker need to be installed. For details on installing these, see the following:

To install the Prisma CLI using npm, run the following command:

  1. npm i -g prisma

For more information, see Set up Prisma (for a new database) in the Prisma documentation.

1. Set up and connect Prisma with the prisma-yb database

To set up a Prisma project, named prisma-yb, run the following command.

  1. prisma init prisma-yb

In order to quickly explore using Prisma with YugabyteDB, we will use the default database and user in the PostgreSQL-compatible YugabyteDB.

When prompted, enter or select the following values:

  • Set up a new Prisma server or deploy to an existing server? Use existing database
  • What kind of database do you want to deploy to? PostgreSQL
  • Does your database contain existing data? No
  • Enter database host: localhost
  • Enter database port: 5433
  • Enter database user: yugabyte
  • Enter database password: [No password, just press Enter]
  • Enter database name (the database includes the schema) yugabyte
  • Use SSL? N
  • Select the programming language for the generated Prisma client: Prisma JavaScript Client

When finished, the following three files have created in the project directory, named prisma-yb:

  • prisma.yml — Prisma service definition
  • datamodel.prisma — GraphQL SDL-based data model (foundation for the database)
  • docker-compose.yml — Docker configuration file

2. Start the Prisma server

To start the Prisma server (in the Docker container) and launch the connected YugabyteDB database, go to the prisma-yb directory and then run the docker-compose command:

  1. cd prisma-yb
  2. docker-compose up -d

You should now have a prismagraphql/prisma container running. You can check that by running docker ps.

3. Set up a sample schema

Open datamodel.prisma and replace the contents with:

  1. type Post {
  2. id: ID! @id
  3. createdAt: DateTime! @createdAt
  4. text: String!
  5. views: Int!
  6. author: User! @relation(link: INLINE)
  7. }
  8. type User {
  9. id: ID! @id
  10. createdAt: DateTime! @createdAt
  11. updatedAt: DateTime! @updatedAt
  12. handle: String! @unique
  13. name: String
  14. posts: [Post!]!
  15. }

4. Deploy the Prisma service (locally)

To deploy the Prisma service, run the following command:

  1. prisma deploy

The Prisma service is now connected to the postgres database and the Prisma UI is running on http://localhost:4466/.

5. Create sample data

Use the Prisma client to create the following sample data. Paste the following code examples, using Prisma’s createUser method, into the left side of a tab, and then click the arrow to process your requests.

For details on writing data with the Prisma client, see Writing Data (JavaScript).

  • Create a user Jane with three postings
  1. mutation {
  2. createUser(data: {
  3. name: "Jane Doe"
  4. handle: "jane"
  5. posts: {
  6. create: [
  7. {
  8. text: "Jane's First Post"
  9. views: 10
  10. },
  11. {
  12. text:"Jane's Second Post"
  13. views: 80
  14. },
  15. {
  16. text:"Jane's Third Post"
  17. views: 25
  18. }
  19. ]
  20. }
  21. }) {
  22. id
  23. }
  24. }

Create user Jane with three postings

  • Create a user John with two postings.
  1. mutation {
  2. createUser(data: {
  3. name: "John Doe"
  4. handle: "john"
  5. posts: {
  6. create: [
  7. {
  8. text: "John's First Post"
  9. views: 15
  10. },
  11. {
  12. text:"John's Second Post"
  13. views: 20
  14. }
  15. ]
  16. }
  17. }) {
  18. id
  19. }
  20. }

Create user John with two postings

6. Query the data

Now that you have created some sample data, you can run some queries to get a taste of using Prisma to query YugabyteDB. In the following examples, you will use the Prisma client to retrieve data. Paste the following code examples into the left side of a tab, and then click the arrow to process your requests.

For details on using the Prisma client to read data, see Reading Data (JavaScript).

Get all users

  1. {
  2. users {
  3. id
  4. name
  5. handle
  6. createdAt
  7. }
  8. }

Results - get all users

Get all posts

  1. {
  2. posts {
  3. id
  4. text
  5. views
  6. createdAt
  7. }
  8. }

Results - get all posts

Get all users – ordered alphabetically

  1. {
  2. users(orderBy: name_ASC) {
  3. name
  4. posts(orderBy: text_ASC) {
  5. text
  6. views
  7. }
  8. }
  9. }

Results - get all posts, ordered alphabetically

Get all posts – ordered by popularity.

  1. {
  2. posts(orderBy: views_DESC) {
  3. text
  4. views
  5. author {
  6. name
  7. handle
  8. }
  9. }
  10. }

Results - get all posts - ordered by popularity

7. Try the Prisma ORM (JavaScript)

In this subsection, you can take a quick look at the Prisma ORM functionality.

Initialize an NPM project.

  1. npm init -y
  2. npm install --save prisma-client-lib

Read and write data

  • Create a file
  1. touch index.js
  • Add the following JavaScript code to index.js:
  1. const { prisma } = require('./generated/prisma-client')
  2. // A `main` function so that we can use async/await
  3. async function main() {
  4. // Create a new user called `Alice`
  5. const alice = await prisma.createUser({ name: 'Alice Doe', handle: 'alice' })
  6. console.log(`Created new user: ${alice.name} (ID: ${alice.id})`)
  7. // Create a new post for 'Alice'
  8. const alicesPost = await prisma.createPost({ text: 'Alice\'s First Post', views: 0, author: {connect: {id : alice.id} }})
  9. console.log(`Created new post: ${alicesPost.text} (ID: ${alicesPost.id})`)
  10. // Get all users ordered by name and print them to the console
  11. console.log("All Users:")
  12. console.log(await prisma.users({ orderBy: 'name_DESC' }))
  13. // Get all of Alice's posts (just one)
  14. console.log("Alice's Posts:")
  15. console.log(await prisma.user( {handle : 'alice'}).posts());
  16. }
  17. main().catch(e => console.error(e))

The code above will create a new user Alice and a new post for that user. Finally, it will list all users, and then all posts by the new user Alice.

  • Run the file:
  1. node index.js

Prisma ORM results

Clean up

Now that you’re done with this exploration, you can clean up the pieces for your next adventure.

  • Stop the YugabyteDB cluster
  1. ./bin/yb-ctl stop

To completely remove all YugabyteDB data/cluster-state you can instead run:

  1. ./bin/yb-ctl destroy
  2. 2. Stop The Prisma container
  3. docker stop <container-id>

To completely remove all Prisma data/tate you can additionally run:

  1. docker rm <container-id>

Note: you can list running containers by running docker ps.