Prisma ClientBasic Data Access

Reading Data (Go)

Overview

The Prisma client is generated from your datamodel. Its API exposes CRUD and other operations for the models defined in the datamodel.

For this page, we'll assume your Prisma project is based on the following datamodel:

type Post {
  id: ID! @id
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
  title: String!
  published: Boolean! @default(value: false)
  author: User
  comments: [Comment!]!
}

type User {
  id: ID! @id
  name: String
  email: String! @unique
  role: Role! @default(value: USER)
  posts: [Post!]!
  comments: [Comment!]!
}

type Comment {
  id: ID! @id
  createdAt: DateTime! @createdAt
  text: String!
  post: Post!
  writtenBy: User!
}

enum Role {
  USER
  ADMIN
}

Whenever a database record is queried using the Prisma client, all scalar fields of that record are fetched. This is true no matter if a single record or a list of records is queried.

For example, the following query returns all scalar fields of a single User:

Go
Result
email := "ada@prisma.io"
user, err := client.User(prisma.UserWhereUniqueInput{
  Email: &email,
}).Exec(ctx)
Copy

In this case, the returned user record will have four properties (that correspond to the scalar fields of the User model): id, name, email and role. The posts and comments fields are both relation fields and are therefore not included in the response.

Here is an example of fetching a list of User records:

Go
Result
users, err := client.Users(nil).Exec(ctx)
Copy

Similar to the previous request, each object inside the users array only has the scalar and no relation fields.

Fetching single records

For each model in your datamodel, there is a method generated in the Prisma client API that allows to fetch single records of that model.

The method is named after the model. For the sample datamodel from above, the three generated methods for fetching single records are:

  • func (client *Client) User(params UserWhereUniqueInput) *UserExec for User
  • func (client *Client) Post(params PostWhereUniqueInput) *PostExec for Post
  • func (client *Client) Comment(params CommentWhereUniqueInput) *CommentExec for Comment

The params input argument for these methods is a struct that has as properties all unique fields of the model. This means, for all three methods, the id field is accepted (as the corresponding models each have an id field annotated as @unique). The params struct for the user method additionaly has an email field.

Examples

Fetch a single post by its id:

Go
Result
id := "cjsx2j8bw02920b25rl806l07"
post, err := client.Post(prisma.PostWhereUniqueInput{
  ID: &id,
}).Exec(ctx)
Copy

Fetch a single user by their email:

Go
Result
email := "ada@prisma.io"
user, err := client.User(prisma.UserWhereUniqueInput{
  Email: &email,
}).Exec(ctx)
Copy

Fetching lists

For each model in your datamodel, there is a method generated in the Prisma client API that allows to fetch a list of the respective records.

The method is named after the model but starts uses the plural form. For the sample datamodel from above, the three generated methods for fetching single records are:

  • func (client *Client) Users(params *UsersParams) *UserExecArray for User
  • func (client *Client) Posts(params *PostsParamsExec) *PostExecArray for Post
  • func (client *Client) Comments(params *CommentsParamsExec) *CommentExecArray for Comment

The input arugment for these functions is a struct that has properties for:

Examples

Fetch all comments:

Go
Result
comments, err := client.Comments(nil).Exec(ctx)
Copy

Fetch a list of users:

Go
Result
users, err := client.Users(nil).Exec(ctx)
Copy

Relations

Prisma client has a fluent API to query relations in your database. Meaning you can simply chain your method calls to navigate the relation properties of the returned records.

Examples

Fetch all the posts of a single user:

Go
Result
posts, err := client.User(prisma.UserWhereUniqueInput{
        Email: &email,
    }).Posts(nil).Exec(ctx)
Copy

Basic filters for lists

Basic filters let you specify certain criteria to constrain which records should be returned in a list. The filters are specified in the Where struct of the params argument which is accepted by any list query.

The type of the Where struct depends on the model for which it was generated.

It is also possible to combine multiple filters using the AND and OR fields.

Examples

Fetch users that have an A in their names:

Go
Result
letter := "A"
usersWithAInName, err := client.Users(&prisma.UsersParams{
    Where: &prisma.UserWhereInput{
        NameContains: &letter,
    },
}).Exec(ctx)
Copy

Fetch users called Ada or Grace:

Go
Result
names := []string{"Ada", "Grace"}
users, err := client.Users(&prisma.UsersParams{
  Where: &prisma.UserWhereInput{
    NameIn: names,
  },
}).Exec(ctx)
Copy

Fetch comments created before December 24, 2019:

Go
Result
christmas := "2019-12-24"
comments, err := client.Comments(&prisma.CommentsParams{
  Where: &prisma.CommentWhereInput{
    CreatedAtLt: &christmas,
  },
}).Exec(ctx)
Copy

Dates and times in the Prisma client API follow the ISO 8601 standard which generally is of the form: YYYY-MM-DDThh:mm:ss. Learn more.

Fetch posts that have prisma or graphql in their title and were created in 2019:

Go
Result
filter1 := "prisma"
filter2 := "graphql"
filteredPosts, err := client.Posts(&prisma.PostsParams{
    Where: &prisma.PostWhereInput{
        Or: []prisma.PostWhereInput{
            prisma.PostWhereInput{
                TitleContains: &filter1,
            },
            prisma.PostWhereInput{
                TitleContains: &filter2,
            },
        },
    },
}).Exec(ctx)
Copy

Relational filters for lists

Relational filters can be used to constrain the returned records on a relation list field. The types used for filtering are similar to basic filters, the major difference is that the filters are not applied on the root level of the method call but when querying a relation (via the fluent API) on a later level.

Examples

Fetch posts by a certain user that were created before christmas:

Go
Result
email := "ada@prisma.io"
christmas := "2019-12-24"
posts, err := client.User(prisma.UserWhereUniqueInput{
    Email: &email,
}).Posts(&prisma.PostsParamsExec{
    Where: &prisma.PostWhereInput{
        CreatedAtLt: &christmas,
    },
}).Exec(ctx)
Copy

Ordering

When querying a list of records, you can order (sort) the list by any scalar field of that model. Each generated method to query a list of records therefore accepts the OrderBy field on the params input struct.

The type of the OrderBy field depends on the scalar fields of the model for which it was generated.

Note that you can always order by createdAt and updatedAt, even when the fields have not been added to your models.

Examples

Sort comments by their creation date (ascending):

Go
Result
orderBy := prisma.CommentOrderByInputCreatedAtAsc
comments, err := client.Comments(&prisma.CommentsParams{
  OrderBy: &orderBy,
}).Exec(ctx)
Copy

Sort users alphabetically by their names (descending):

Go
Result
orderBy := prisma.UserOrderByInputNameDesc
users, err := client.Users(&prisma.UsersParams{
    OrderBy: &orderBy,
}).Exec(ctx)
Copy

Aggregations

You can submit aggregation queries via connection queries. The following aggregation functions are supported:

  • count: Counts the number of records in a list
  • avg (coming soon): Computes the average of a list of numbers.
  • median (coming soon): Computes the median of a list of numbers.
  • max (coming soon): Returns the greatest element of a list of numbers.
  • min (coming soon): Returns the smallest element of a list of numbers.
  • sum (coming soon): Computes the sum of a list of numbers.

See this GitHub issue to learn more about the upcoming aggregation functions.

Examples

Count the number of post records:

Go
Result
const postCount: number = await prisma
  .postsConnection()
  .aggregate()
  .count()
Copy