relationMode = "prisma": an update that writes no linking field still reads the dependent rows of every onUpdate: Restrict relation

Open
#30,874 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
72/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
mariadb, mysql, typescript

Research direction

Start with emulate_on_update_restrict in query-compiler/core/src/query_graph_builder/write/utils.rs and the existing cases in query-engine/connector-test-kit-rs/query-engine-tests/tests/new/ref_actions/on_update/restrict.rs. Check how the function determines whether linking fields are updated, then add coverage for a name-only update that should not read dependent rows. Done means that update skips the child query while an update to a linking field still reads dependents and rejects with P2014 when restricted.

Written by the indexing model from the issue text.

Description

Written by an AI agent (Claude) on behalf of @jasonkuhrt.

Package and version

prisma 7.10.0 and @prisma/client 7.10.0 (query compiler, @prisma/adapter-mariadb 7.10.0), engines 0edf323efd1d98336f3f0a68684b56f689b900d3.

What happened?

With relationMode = "prisma", an update that writes no field a relation links on still reads the dependent rows of every onUpdate: Restrict relation, then discards them.

await prisma.parent.update({ where: { id: 1 }, data: { name: 'after' } })

The SQL it sends (from the client's query events):

SELECT `Parent`.`id` FROM `Parent` WHERE (`Parent`.`id` = ? AND 1=1) LIMIT ? OFFSET ?
SELECT `Child`.`id`, `Child`.`parentId` FROM `Child` WHERE (1=1 AND `Child`.`parentId` IN (?))
UPDATE `Parent` SET `name` = ? WHERE (`Parent`.`id` IN (?) AND (`Parent`.`id` = ? AND 1=1))
SELECT `Parent`.`id`, `Parent`.`name` FROM `Parent` WHERE `Parent`.`id` = ? LIMIT ? OFFSET ?

The second statement cannot change the outcome. The restriction can only fail when the update writes a linking field (Parent.id here), and this update writes name alone. The cost is one read per Restrict relation on the updated model, on every update. In our application a document-editor save paid five of them, about 179 ms of a save of about 1,010 ms.

What did you expect to happen?

No dependent read when the update writes no linking field. When it does write one, as data: { id: 2 } does, the read and its P2014 stay exactly as they are today.

Minimal reproduction
datasource db {
  provider     = "mysql"
  relationMode = "prisma"
}

generator client {
  provider = "prisma-client-js"
}

model Parent {
  id       Int     @id
  name     String
  children Child[]
}

model Child {
  id       Int    @id
  parentId Int
  parent   Parent @relation(fields: [parentId], references: [id], onUpdate: Restrict, onDelete: Restrict)

  @@index([parentId])
}
const prisma = new PrismaClient({ adapter, log: [{ emit: 'event', level: 'query' }] })
prisma.$on('query', ({ query }) => console.log(query))

await prisma.parent.create({ data: { id: 1, name: 'before' } })
await prisma.child.create({ data: { id: 1, parentId: 1 } })

// Reads Child, although only `name` changes:
await prisma.parent.update({ where: { id: 1 }, data: { name: 'after' } })

// Reads Child and rejects with P2014, as it should:
await prisma.parent.update({ where: { id: 1 }, data: { id: 2 } })

Against MySQL 8.4.11, the first update logs the four statements above and succeeds. The second logs the same Child read and rejects with P2014.

Environment
  • macOS (arm64), Node.js v24.22.1
  • MySQL 8.4.11 in Docker, through @prisma/adapter-mariadb 7.10.0
  • relationMode = "prisma", no database foreign keys
Additional context

The read comes from emulate_on_update_restrict in query-compiler/core/src/query_graph_builder/write/utils.rs (lines 821–860 on prisma-engines main, unchanged since 7.10.0). It inserts the dependent read first, then computes linking_fields_updated, and uses that only to decide whether the read's rows must be empty. The shape dates from prisma/prisma-engines#3194, the fix for #13766, which made the restriction depend on the linking fields but kept the read for every update.

Returning before the read when no linking field is written keeps every current result:

@@ -824,11 +824,7 @@ pub fn emulate_on_update_restrict(
     parent_node: &NodeRef,
     child_node: &NodeRef,
 ) -> QueryGraphBuilderResult<()> {
-    let noop_node = graph.create_node(Node::Empty);
     let relation_field = relation_field.related_field();
-    let child_model_identifier = relation_field.related_model().shard_aware_primary_identifier();
-    let read_node = insert_find_children_by_parent_node(graph, parent_node, &relation_field, Filter::empty())?;
-
     let linking_fields = relation_field.linking_fields();
 
     // Unwraps are safe as in this stage, no node content can be replaced.
@@ -838,6 +834,14 @@ pub fn emulate_on_update_restrict(
         .into_iter()
         .any(|parent_pk| parent_update_args.get_field_value(&parent_pk.db_name()).is_some());
 
+    if !linking_fields_updated {
+        return Ok(());
+    }
+
+    let noop_node = graph.create_node(Node::Empty);
+    let child_model_identifier = relation_field.related_model().shard_aware_primary_identifier();
+    let read_node = insert_find_children_by_parent_node(graph, parent_node, &relation_field, Filter::empty())?;
+
     graph.create_edge(
         &read_node,
         &noop_node,
@@ -845,11 +849,7 @@ pub fn emulate_on_update_restrict(
             child_model_identifier,
             RowSink::Discard,
             // If any linking fields are to be updated and there are already connected children, then fail
-            if linking_fields_updated {
-                Some(DataExpectation::empty_rows(RelationViolation::from(relation_field)))
-            } else {
-                None
-            },
+            Some(DataExpectation::empty_rows(RelationViolation::from(relation_field))),
         ),
     )?;

We run exactly this change today, as a patch of the MySQL fast query compiler's WASM built from 0edf323e. Comparing its query plans with the shipped compiler's, on our schema: an update of a model with three Restrict relations that writes no linking field loses all three reads, and an update that writes a linking field keeps a byte-identical plan. The existing tests in query-engine/connector-test-kit-rs/query-engine-tests/tests/new/ref_actions/on_update/restrict.rs (update_parent and the *_failure cases) cover the outcomes. None asserts which queries run, so a test that a name-only update issues no Child query would be new.

Related: #15759 asks for a way to turn emulation off, which this does not need; #30761 is a similar wasted child query for include.

Dominant language
TypeScript
Stars
47.8k
Forks
2.6k
Avg merge
1d 21h
Merged PRs (30d)
227

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from prisma/orm

All issues in prisma/orm

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.