Skip to content

Preview feature feedback: Views #17335

Open

Description

@floelhoeffel

Views support is in early preview and you can learn about it in our documentation.

Please share your feedback about the views functionality released in v4.9.0 in this issue.

  • If you encounter a bug, please open a bug report in this repo.
  • If the feature is working well for you, please share this in a comment below or leave a 👍 on this issue.
  • If you have any questions, don't hesitate to ask them in the Prisma Slack community

GA planned for March-August 2025

Activity

  1. added
    topic: previewFeatures
    on Jan 16, 2023
  2. self-assigned this
    on Jan 16, 2023
  3. Ustice commented on Jan 17, 2023

    @Ustice

    The general process is that we add the SQL to generate the views by hand to our migrations, and this new feature gives us a way to describe those views, and query them with the prisma client.

    Is this correct?

  4. floelhoeffel commented on Jan 18, 2023

    @floelhoeffel
    Author

    @Ustice Exactly - the next step is we add introspection support.

  5. jonschlinkert commented on Jan 19, 2023

    @jonschlinkert

    I love this feature, but I have some questions. How do views determine field associations? In the following, how would the UserInfo view know which table the type field belongs to, and how does UserInfo know that it's associated with User?

    view UserInfo {
      id    Int    @id
      name  String
      type  String
    }
    
    model User {
      id      Int      @id @default(autoincrement())
      name    String
      type    String?
      profile Profile?
    }
    
    model Profile {
      id     Int    @id @default(autoincrement())
      type   String
      user   User   @relation(fields: [userId], references: [id])
      userId Int    @unique
    }
  6. janpio commented on Jan 19, 2023

    @janpio
    Contributor

    @jonschlinkert That happens via the underlying SQL query that is used to create a view UserInfo that has three fields id, name and type? See this documentation section for an example for exactly this model: https://www.prisma.io/docs/concepts/components/prisma-schema/views#how-to-add-views-to-your-prisma-schema The view block just tells Prisma which fields to build from the columns the view returns.

    Right now you can not define this SQL query in Prisma schema at all to migrate it (via migrate dev or db push and have to create this manually, outside of Prisma. In the future that might change.

    But, we are already pretty certain that we will not be able to represent these queries with Prisma schema syntax, so for example a "mapping" or "field associations between UserInfo and User". A view can be defined via any SQL query - which includes an infinite number of possibilities, so we found no way to reliably represent that in Prisma schema.

    Does that explain the current state and where this might go?

  7. jonschlinkert commented on Jan 20, 2023

    @jonschlinkert

    Does that explain the current state and where this might go?

    Yes, got it. I seem to have missed the part that the SQL query needs to be created manually, which makes sense. It's much more clear now, thank you.

  8. sixers commented on Jan 23, 2023

    @sixers

    ❤️ I love this feature. I was able to move complex multi-table pricing logic, which had to be repeated multiple times in the code to a centralized view. What I liked the most is that I can still model relationships and they just work - which means I can create views which only hold custom computed values, and join them with the original model to get the non-computed fields.

    The only annoyance I had so far is the requirement to have an @id field, which doesn't make sense for my table, but I had to create a fake column anyway.

    I don't expect this feature to be super popular because it requires SQL knowledge and is probably only beneficial for more complex table structures, but for me it is very important and simplifies a lot, so thank you!

  9. janpio commented on Jan 24, 2023

    @janpio
    Contributor

    Would you have been able to easily identify any of the columns as @unique in your view? It will be quite some while until we can fully get rid of the limitation of needing a field to uniquely identify a row, but maybe @unique is the better choice than @id.

  10. sixers commented on Jan 24, 2023

    @sixers

    My view is a cross join between 2 tables, so I could use compound key (id from first table, id from second table), but not a single column.

    I create a fake id column like this:

    (first.id - 1) * (( SELECT max(id) AS max
               FROM second)) + second.id AS id
  11. janpio commented on Jan 24, 2023

    @janpio
    Contributor

    You would also be able to use @@unique([first_id, second_id]) as a compound unique if you include both fields in the view. (Sorry, missed to mention that above - we would of course support both @unique for individual columns but also @@unique for when columns need to be combined.)

  12. 75 remaining items

  13. GauBen commented on Jul 29, 2025

    @GauBen
    Contributor

    Hi there, the latest Prisma release (6.13.0) broke the ability to use relations with views:

    Error validating: The field `author` is part of a relation that references a view. Relations currently cannot be used with views.
    

    This is a hard blocker on my end and it prevents upgrading (views are useful because I'm able to link them to models). I hope we have a way to declare relations between views and models for the GA of the feature.

  14. aqrln commented on Jul 30, 2025

    @aqrln
    Member

    @GauBen we likely won't. It is exactly due to us moving the views preview feature closer to GA and stabilizing its API that we have decided to remove support for relationships involving views after careful consideration, in addition to some other Client API restrictions. In exchange, we have lifted the requirement to have a unique field in the view. In fact, you can't mark any fields inside the view blocks as @id or @unique anymore (@unique may be supported for materialized views in the future).

    Relationship support for views in the way we provided was inherently unsafe and had footguns we saw users constantly running into, causing correctness issues in their applications. Some of those problems were unsolvable without limiting other aspects of the views support. It is possible to design and re-introduce a safe, limited subset of the former relationship APIs for views though. If you relied on this, please open a feature request and tell us about your use case!

  15. sixers commented on Jul 30, 2025

    @sixers

    It's very unfortunate, my primary use case for views has been to add computed fields to models that involve complex SQL operations and aggregations. I've implemented these as views and then connected them to the main model via relationships. It's a key use case for me, and it seems it's no longer supported.

  16. ajmnz commented on Jul 30, 2025

    @ajmnz

    Totally agree with @GauBen and @sixers. Relationship support was a key selling point of views for us too. It enabled powerful use cases that are now hard to replicate without it, forcing us to fall back to raw SQL. Would really like to see a safe subset brought back before GA.

  17. clemens commented on Jul 30, 2025

    @clemens
    Contributor

    First of all, to everyone who's having issues with the most recent 6.13.0 release's changes to views, here's a workaround that seems to work for our codebase:

    • Enable the externalTables preview feature and add the views that use unsupported features to the external tables list
    • Change your views to be models (as in: view SomeView becomes model SomeView)

    It's a bit clumsy and the downside is that it adds methods like insert, update etc. to the models, which obviously won't work. But IMO that's more a developer experience concern than an actual problem: Since you've been using views (and have been using the view keyword), you're hopefully not using modifying methods – and if you do, then you have a problem already (with or without the update to 6.13.0).


    Now a thing for this particular discussion thread.

    @aqrln I might be wrong here, but I think these recent changes go against your official ORM releases and maturity levels. There are two statements in this guide that stand out:

    Preview: [...] Users can count on the feature or product and associated API to be mostly stable unless stated otherwise in the release notes and documentation.

    I've done a quick search in previous release notes and couldn't spot any mention of "we're unsure about supporting indexes, constraints and relationships on views, so we might remove them without replacement".

    Breaking changes can still be rolled out in MINOR but only for opt-in Preview and Early Access features that are not active by default (e.g. via a Preview feature flag or a specific opt-in option or new CLI command).

    This IMO directly contradicts the above. So at best, it's confusing – and at the worst, one can't know which is true for which case.

    This is particularly striking to me, since for the case of views, it seems that this has been declared as "Preview" for almost 2.5 years (2 major versions ago). Add to that that Prisma literally until 2 weeks ago enforced adding a unique identifier and told you it's because it's treated the same as regular models and we end up in the current situation – which is less than optimal. IMO it doesn't fit Prisma's maturity level to instruct people that they need to add a unique identifier to their views, because otherwise it won't work and then do a full 180 on it and tell people that what they've had to do for 2.5 years not only isn't necessary anymore but in fact breaks altogether.

    I would encourage the Prisma team to take one of two steps to remedy the situation:

    • Roll back the change altogether and introduce an upgrade path; maybe even only in Prisma 7, because even if it is a "Preview" feature, it's arguably a VERY breaking change
    • If that's not possible or interferes too much with your overall process and roadmap, maybe you could verify my workaround mentioned at the top of this post – and if it does work, you could consider including it in the docs for views

    If you want to go with option 2 and have verified that it's compatible, I'm happy to submit a PR with better phrasing and examples than above for the docs repo.

  18. khalilsarwari commented on Jul 31, 2025

    @khalilsarwari

    We've been using the views preview feature for quite some time now as well, similar use case as mentioned above in which heavy computations are stored and then fetched via relationships. This most recent version invalidates this pretty common and reasonable use case, which it seems many people are reliant upon.

    I can understand the downsides to the original views setup with the footguns, but at the same time it could be leveraged (with care) in a way that did not seem janky and served its purpose well. I would also like to request rolling back the change for now - not only would it improve the impression of stability for prisma, but it would give some more time to think through and potentially incorporate a safe version of the relationship APIs from the get-go to prevent breakage.

  19. dvins commented on Aug 13, 2025

    @dvins

    @GauBen we likely won't. It is exactly due to us moving the views preview feature closer to GA and stabilizing its API that we have decided to remove support for relationships involving views after careful consideration, in addition to some other Client API restrictions. In exchange, we have lifted the requirement to have a unique field in the view. In fact, you can't mark any fields inside the view blocks as @id or @unique anymore (@unique may be supported for materialized views in the future).

    Relationship support for views in the way we provided was inherently unsafe and had footguns we saw users constantly running into, causing correctness issues in their applications. Some of those problems were unsolvable without limiting other aspects of the views support. It is possible to design and re-introduce a safe, limited subset of the former relationship APIs for views though. If you relied on this, please open a feature request and tell us about your use case!

    The silence from the Prisma team on this issue (and the half dozen related ones since opened) is concerning. What's more troubling: the lack of engagement, or that these design decisions suggest a fundamental misunderstanding of how enterprises actually use views in relational databases?

  20. videvian commented on Aug 13, 2025

    @videvian

    @GauBen we likely won't. It is exactly due to us moving the views preview feature closer to GA and stabilizing its API that we have decided to remove support for relationships involving views after careful consideration, in addition to some other Client API restrictions. In exchange, we have lifted the requirement to have a unique field in the view. In fact, you can't mark any fields inside the view blocks as @id or @unique anymore (@unique may be supported for materialized views in the future).
    Relationship support for views in the way we provided was inherently unsafe and had footguns we saw users constantly running into, causing correctness issues in their applications. Some of those problems were unsolvable without limiting other aspects of the views support. It is possible to design and re-introduce a safe, limited subset of the former relationship APIs for views though. If you relied on this, please open a feature request and tell us about your use case!

    The silence from the Prisma team on this issue (and the half dozen related ones since opened) is concerning. What's more troubling: the lack of engagement, or that these design decisions suggest a fundamental misunderstanding of how enterprises actually use views in relational databases?

    They reverted some changes in the latest release https://github.com/prisma/prisma/releases/tag/6.14.0
    Still no @id, but now @unique and relations work again.

    They did delete some other things in that release like prisma.$use and marked metrics as deprecated without updating docs, so all examples still show how to use metrics with prisma.$metrics. But it works for now, so no complaints. Though I guess, they could've deleted $use in a major version instead of a minor one.

  21. dvins commented on Aug 13, 2025

    @dvins

    They reverted some changes in the latest release https://github.com/prisma/prisma/releases/tag/6.14.0 Still no @id, but now @unique and relations work again.

    They did delete some other things in that release like prisma.$use and marked metrics as deprecated without updating docs, so all examples still show how to use metrics with prisma.$metrics. But it works for now, so no complaints. Though I guess, they could've deleted $use in a major version instead of a minor one.

    That's great news, though bad form nothing communicated on any of the half dozen threads this particular reversion was coming or that it dropped.

  22. aqrln commented on Aug 19, 2025

    @aqrln
    Member

    Hey folks, I'd like to clear up some misunderstandings and provide an update for you. I was going to do this a while ago but unfortunately this fell through the cracks for which I apologize. We did hear you, and we did re-prioritize work and act on your feedback.

    @ethos-vitalii:

    They reverted some changes in the latest release 6.14.0 (release

    What we did wasn't just "revert" the changes. We now have a more robust implementation that avoids the pitfalls of the previous implementation, built on top of the work done in 6.13.0 (which, in turn, wasn't just "removing" the functionality, that was more of consequence of the changes than the main change itself). With Prisma 6.14 and newer, views are more of a first class citizen and aren't treated the same as models anymore. This means that:

    • Views have their own validations in Prisma schema language and don't trigger model-specific validations that don't apply to them.
    • Views don't need to have an ID or unique fields. The available APIs depend on whether there are unique fields. Before Prisma 6.13.0, Prisma forced you to artificially declare at least some field as unique, which led to issues when none of them were actually unique. I understand that those of you who have left feedback in this issue took care to make sure these annotations were correct, but it wasn't the case for many other users who were running into serious correctness issues in their applications because of this. Marking a field as unique is now a conscious opt-in rather than something that ORM forces you to do, and views are now usable in the Client either way, just with different API affordances.

    Still no @id, but now @unique and relations work again.

    You don't need an @id, there was no practical difference between using @id or @unique in views before 6.13.0. The distinction between them only matters for models, and mostly for Migrate, because they create different kinds of constraints and indexes. Views aren't yet supported by Migrate, and regular (non-materialized) views have no indexes or constraints. @unique for views in 6.14.0+ now has clearly defined semantics (and its own validations in PSL that differ from @unique for models) of an unchecked assertion that you can use to tell Prisma that you guarantee the uniqueness of the field. We will later support real database-level unique indexes when we add support for materialized views.

    @clemens

    I might be wrong here, but I think these recent changes go against your official ORM releases and maturity levels

    Thank you, this is a very good callout. I do agree with you that de-facto views feel like an early access feature, given the lack of a stable and validated product surface, especially support in Migrate. I can't comment on whether it satisfied the formal criteria for "Preview" back when the feature was introduced because I don't know. However, you may have noticed that nowadays we use the "Early Access" status consistently and all large features go through this stage, rather than starting in "Preview" immediately. We are committed to bringing our long-standing preview features to GA, and you can be confident in the clarity of the maturity levels of all new features.

  23. sixers commented on Aug 19, 2025

    @sixers

    🙌🏻 Thank you for listening to the community.

  24. jdpt0 commented on Aug 21, 2025

    @jdpt0

    Hi @aqrln, thanks for listening to the feedback. My team, like many others here, would have been severely impacted by this change, so glad to hear you took this on board.

    You mention:

    With Prisma 6.14 and newer, views are more of a first-class citizen and aren't treated the same as models anymore.

    Does this also mean there will be future updates that allow us to distinguish between a model and a view in the DMMF? This would be very handy, as we're using Prisma Extensions to generate factories for our models. The change to views that removes write support (while itself is a welcome change) breaks this extension and makes it very hard to work around, given that we can't easily distinguish between a view and a model.

  25. AjaniBilby commented on May 11, 2026

    @AjaniBilby

    It looks like all of the pieces for this feature already exist in Prisma for this to be properly supported (at least for Postgres servers), they just need to be connected together.

    I just want to confirm if this would be a potential method for support?

    If this is a valid approach, if this feature isn't in by Christmas I might be able to get my company to dedicate some resources to it to make a PR to implement the below.
    Either that or if someone else sees this and has the motivation they could try?


    View Syncing

    The bare-minimum should be detecting changes, and automatically creating a new migration.
    Since I have already had headaches dealing with database generated columns, it's clear Prisma doesn't currently have a way to syntatically comparing if two SQL statements are identical. But you can get the DB to do the heavy lifting for this.

    Since I haven't looked into how the internals for migration detection work I'm just going to write it as a prisma transaction for demonstration purposes.

    for (const view of views) { // could also be used for detecting db-drift on a shadow db
      try {
        await prisma.$transaction(async (tx) => {
        	// create it as a new view so the database will parse and normalize the syntax
        	const id  = Math.floor(Math.random() * 1679615).toString(36).padStart('0', 4);
        	const tmp = `_prisma_view_tmp${id}`;
    
         	// compare the database representations of the view (always unmaterialized to avoid excessive computation)
        	await tx.$executeRawUnsafe(`CREATE VIEW "${tmp}" AS ${view.sql}`); // sql should be checked for erroneous semi-columns
    
         	const [ match ] = await tx.$queryRawUnsafe(`SELECT pg_get_viewdef('"${view.name}"'::regclass) = pg_get_viewdef('"${tmp}"'::regclass) as "match"`);
         	if (!match) view.markOutOfDate();
    
         	// roll the transaction back to remove the created view (could use drop instead)
         	throw new Error('rollback');
        });
      } catch { /* using errors for rollback */ }
    }

    Then views should be stored in their own folder like sql.
    The simplest method would be the file name has to match the view name, or an extra attribute could be added to the view to specify the filename - though I feel like that might be excessive bloat.
    Possibly the lookup for a view's file should be case in-sensitive to deal with window/unix compatibility issues that might otherwise arrise, and ethically a project should have two views with the same name seperated by casing.


    Type Validation

    Since typedSql is already able to resolve the return types of a query, you should be able to piggy back off that to determine the output type of the view, and verify it matches with the schema in the .prisma.

    At bare minimum you could repurpose parts of the typedSql code to at least vaildate the query before attempting to check for migration


    Nice to Haves

    There should be an @stored attribute which could be added to the view itself to enable indexing and then it needs to be created as MATERALIZED.
    The materialized state can be checked with SELECT relkind = 'm' as "materialized" FROM pg_class WHERE relname = ${name}; to determine if the view needs to be created in the correct mode.


    I personally do not have enough experience with MySQL to comment on it's equivalents for this, but I assume where are some.


    In the mean time for anyone else here, I have made a little script I will use to help check if my views definition files match what's in my development db, so I can synchonise any view updates easily.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: previewFeaturestopic: views

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions