Writing Data
Create Queries

Create Queries

create and create_many allow you to easily create one or many records.

A model's required fields need to be provided as individual arguments to the arguments of create or in a tuple for `create_many', whereas optional fields can be provided in a Vec after all the required fields.

When providing the value of an optional field, it is necessary to wrap the value in a 'field identifier' so that the client knows which field to set. These usually look like model::field::set. This is not required for required fields as they get their own position in the argument list.

Nested creates are not supported yet.

The examples use the following schema:

generator client {
    provider = "cargo prisma"
    output = "src/prisma.rs"
}
 
model Post {
    id        String   @id @default(cuid())
    createdAt DateTime @default(now())
    updatedAt DateTime @updatedAt
    published Boolean
    title     String
    content   String?
    desc      String?
 
    comments Comment[]
}
 
model Comment {
    id        String   @id @default(cuid())
    createdAt DateTime @default(now())
    content   String
 
    post   Post   @relation(fields: [postID], references: [id])
    postID String
}

Create

The following example creates a post and overwrites its autogenerated id field.

use prisma::post;
 
let post: post::Data = client
    .post()
    .create(
        // Required fields are individual arguments.
        // Wrapping their values is not necessary.
        true,
        "what up".to_string(),
        // All other fields can be passed in the last argument
        vec![
            // Generated fields can be overwritten like regular fields
            post::id::set("id".to_string()),
            // Non-required fields require being wrapped in an Option
            post::content::set(Some("content".to_string()))
        ]
    )
    .exec()
    .await?;

Connecting Relations

The connect function of a relation field module can be used to connect new records with existing ones. It takes a single unique filter as an argument.

The following example creates a new comment and links it to a post.

use prisma::{comment, post};
 
let comment: comment::Data = client
    .comment()
    .create(
        "content".to_string(),
        // If post wasn't required, then the equals() would need
        // to be wrapped in comment::post::connect(..).
        post::id::equals("id".to_string())
        vec![]
    )
    .exec()
    .await?;

Connecting records like this is equivalent to directly setting the values of the relation's foreign keys, eg. setting post_id from the above example with comment::post_id::set().

Create Many

create_many can be used to create many records of a single model type. It accepts a Vec of tuples with a similar shape as the arguments to create, except only scalar fields can be provided. Connecting relations using relation field operations is not possible.

To assist in constructing tuples of the right shape, each model module contains a create_unchecked function that accepts a model's scalar fields and returns the correct tuple. unchecked is a Prisma term, describing inputs that only accept a model's scalar fields.

SQLite support for create_many is UNSTABLE, but can be enabled by adding the sqlite-create-many feature to prisma-client-rust and prisma-client-rust-cli in your Cargo.toml files.

The following example iterates an array of titles, turns it into tuples and creates multiple posts.

use prisma::post;
 
let titles = [
    "Title 1",
    "Title 2",
    "Title 3"
]
 
let posts: i64 = client
    .post()
    .create_many(
        titles
            .iter()
            .map(|title| post::create_unchecked( 
                true,
                title.to_string(),
                vec![]
            ))
            .collect() // Necessary to create a Vec
    )
    .exec()
    .await?;

Skip Duplicates

The create_many builder has a skip_duplicates function which can be used to stop an error from being thrown if a unique constraint is violated, instead conflicting records will be ignored and the rest will be created.

client
    .post()
    .create_many(..)
    .skip_duplicates() // No error if unique violation is broken
    .exec()
    .await?