[Prisma 8] SQL builder: guarded insert — insert from a select, and project bound values in a select

Open
#30,985 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
42/100
Issue type
Feature
Clarity
Clearly specified
Activity status
Active
Tech stack
postgresql, typescript
Domain
backend, databases

Research direction

Read packages/2-sql-family/4-lanes/sql-builder/src/types/table-proxy.ts and packages/2-sql-family/4-lanes/relational-core/src/ast/types.ts to trace how inserts and selects are represented; compare with #30488 for insert-from-select behavior. Then inspect the SQL builder's parameter projection and column codec paths. Done means insert-from-select is type-checked against target columns and bound values can be projected using the target column's codec, with defaults behavior resolved.

Written by the indexing model from the issue text.

Description

kind/feature

What we need

A way to insert a row only when a condition holds, checked in the same SQL statement. In Postgres:

INSERT INTO "Document" ("id", "projectId", "title")
SELECT $1, p."id", $2
FROM "Project" p
WHERE p."id" = $3
  AND EXISTS (
    SELECT 1 FROM "Membership" m
    WHERE m."workspaceId" = p."workspaceId" AND m."userId" = $4 AND m."role" IN ('admin', 'developer')
  )
RETURNING "id";

If the condition is false, the select returns no row and nothing is inserted.

Following the discussion with the ORM team, this belongs in the SQL builder rather than the ORM create API. The builder already has most of what is needed. Two pieces are missing.

1. insert that takes a select

insert accepts literal rows only (packages/2-sql-family/4-lanes/sql-builder/src/types/table-proxy.ts), and InsertAst holds rows only (packages/2-sql-family/4-lanes/relational-core/src/ast/types.ts). This is the same gap as #30488, which hit it in a data migration.

sql.public.Document.insert(
  sql.public.Project
    .select((f, fns) => ({ id: fns.param(documentId), projectId: f.id, title: fns.param(title) }))
    .where((f, fns) => fns.and(fns.eq(f.id, projectId), /* access predicate */)),
).returning('id');

The select's columns would be type-checked against the target table's columns, as #30488 suggests.

2. Projecting a bound value in a select

The guarded insert mixes fixed values (a new ID, a title) with columns from the guard row. The builder's functions cover comparisons, and/or, exists/in and aggregates, but nothing projects a parameter. Something like fns.param(value) (or a typed literal), encoded through the target column's codec, would cover it.

Why

We put authorization in the statement that reads or writes data, so a member whose access was revoked cannot write through a request that started before the revocation. Reads and updates already do this through where predicates. Inserts cannot, so we wrote about 30 of them as raw SQL with json_populate_record(NULL::"Table", $1::json). That loses what the builder gives us:

  • Table and column names are strings, so a renamed column passes the type check and fails at runtime.
  • A misspelled JSON key is ignored, and the column silently gets NULL or its default.
  • Values such as bytea and timestamps are encoded by hand instead of by the codecs.

Open question

Column defaults: #30488 asks whether an insert-from-select applies the contract's defaults (for example @default(uuid(7))) per row, or requires the select to supply every column. For our use, requiring the select to supply them is fine.

Related

  • #30488: the same insert-from-select capability, for data migrations. Part 1 here duplicates it; part 2 is new.
  • #30730: conditional DO UPDATE … WHERE for upsert. With part 1 and onConflict, it would cover our insert-or-update cases.

Environment

  • @prisma/orm-postgres 8.0.0-rc.13, @prisma/orm-family-sql 8.0.0-rc.13, prisma 8.0.0-rc.19
  • PostgreSQL
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.