prisma icon indicating copy to clipboard operation
prisma copied to clipboard

Add support for database views

Open divyenduz opened this issue 7 years ago • 116 comments

Problem

In a database, a view is the result set of a stored query on the data, which the database users can query just as they would in a persistent database collection object. Unlike ordinary base tables in a relational database, a view does not form part of the physical schema: as a result set, it is a virtual table computed or collated dynamically from data in the database when access to that view is requested. Changes applied to the data in a relevant underlying table are reflected in the data shown in subsequent invocations of the view.

Prisma does not currently support database views.

Suggested solution

No suggestion.

Alternatives

The current workaround available is to manage views manually and query views by using the raw SQL API.

~Or use the documented workarounds https://www.prisma.io/docs/guides/database/advanced-database-tasks/sql-views-postgres or https://www.prisma.io/docs/guides/database/advanced-database-tasks/sql-views-mysql but make sure to read the "Limitations" section properly!~

Alternatively you can treat a "fake model" to your Prisma schema that has the same structure than the view results. Note that future Introspection might drop this "model" and future Migrations might try to create a table of that name - so make sure to handle that.

Additional context

Frameworks like Ruby on Rails don't support views out of the box, but there are 3rd party libraries available (scenic for Rails).

Original issue

Prisma 2 init doesn't print MySQL views into the Prisma schema, this issue tracks support for introspection of views for being able to use it with brownfield projects.

This ties into this larger epic: https://github.com/prisma/prisma2/issues/156

We also need to (possibly) add support for creating views in Prisma schema file, this issue tracks that for the time being before we have clarity on this topic and we can split it into multiple issues.

This issue also tracks views across all connectors:

  • [ ] MySQL
  • [ ] Postgres
  • [ ] SQLite

divyenduz avatar Oct 07 '19 13:10 divyenduz

This applies to more than MySQL I'm hoping, right? PostgreSQL would be another good one to get an api into views for.

jeffvandyke avatar Apr 02 '20 19:04 jeffvandyke

@jeffvandyke Thank you, I updated the issue to reflect that.

divyenduz avatar Apr 03 '20 04:04 divyenduz

I'm not sure I understand your issue.

I believe that this is more a problem of its application than of the prisma. Do you just need to make the options you need with @prisma/client, or is it possible to update or register data accidentally?

felinto-dev avatar Jun 01 '20 23:06 felinto-dev

I'm not sure I understand your issue. I believe that this is more a problem of its application than of the prisma.

Hello @felinto-dev,

this issue describes a feature request to add support for database views. It is not directly related to views in the application layer, but rather about a database construct called view.

Please let me know if this helps.

albertoperdomo avatar Jun 02 '20 10:06 albertoperdomo

Some notes from my recent experience using Prisma 2 and creating a few SQL views:

I followed the steps found in the docs here: https://www.prisma.io/docs/guides/database-workflows/sql-views-postgres And it works to manually add the view to the database with raw SQL and add a model to the Prisma datamodel file, but what ends up happening is that every time I run npx prisma migrate save --experimental I have to manually delete the creation of my view from the migration steps.

Likewise, when I introspect the database my views don't show up at all.

codingmatty avatar Jul 17 '20 01:07 codingmatty

@codingmatty Yes, that guide is meant to be used with introspection. Using migrate will fail there as it will try to create a table with same name as the view.

Please wait till we roll out support for database views natively.

pantharshit00 avatar Jul 17 '20 09:07 pantharshit00

Would it also be possible to support stored procedures? 🤔

MichalLytek avatar Dec 28 '20 10:12 MichalLytek

@MichalLytek Prisma does not yet support this and I am not sure we would add support for this in the near future.

As a workaround, you should be able to create stored procedures now with Prisma Migrate by modifying the SQL files. Prisma Client won't be of much help interacting with those but you should be able to use queryRaw or executeRaw.

albertoperdomo avatar Jan 04 '21 18:01 albertoperdomo

Prisma Client won't be of much help interacting with those but you should be able to use queryRaw or executeRaw.

That's what I'm talking about - ability to call store procedure in a type-safe manner:

const results = await prisma.$procedures.myProcedure(myParam1, myParam2);

MichalLytek avatar Jan 04 '21 18:01 MichalLytek

That's what I'm talking about - ability to call store procedure in a type-safe manner

Looks like something that you could propose by submitting a feature request. If it gets some traction within the community we could potentially look into it.

albertoperdomo avatar Jan 04 '21 18:01 albertoperdomo

Prisma Client won't be of much help interacting with those but you should be able to use queryRaw or executeRaw.

That's what I'm talking about - ability to call store procedure in a type-safe manner:

const results = await prisma.$procedures.myProcedure(myParam1, myParam2);

I would understand why you would need if moving an application to Prisma but I don’t really see any uses for it with a new application.

Anything you can achieve in a stored procedure you can also achieve in the node server with Prisma (correct me if I’m wrong).

I think the optimal solution is to implement/reimplement your stored procedures in a Node function, removing the load from the database (as far as I know is easier to scale horizontally a node application than a database).

dualmacops avatar Feb 07 '21 19:02 dualmacops

@dualmacops

Anything you can achieve in a stored procedure you can also achieve in the node server with Prisma (correct me if I’m wrong).

There are exceptions where stored procs make sense, for example when gathering data from several tables into a temp table for paging/sorting. I think this will be more efficient/maintainable to be a stored procedure 🤔

MichalLytek avatar Feb 12 '21 14:02 MichalLytek

+1 to that. Stored procedures goes hand is hand with transactions that require updates of multiple table and the ability to rollback in case of a failure in one of the updates.

alonbilu avatar Feb 15 '21 06:02 alonbilu

@alonbilu I think you are talking about the ability of doing atomic operations, you can do that with Prisma transaction-api "The $transaction API is generic solution to independent writes that allows you to run multiple operations as a single, atomic operation - if any operation fails, Prisma rolls back the entire transaction." https://www.prisma.io/docs/guides/prisma-guides/prisma-client-transactions-guide/#transaction-api

dualmacops avatar Feb 15 '21 12:02 dualmacops

but what ends up happening is that every time I run npx prisma migrate save --experimental I have to manually delete the creation of my view from the migration steps.

I created a script to workaround this issue. It deletes the manually created view models and their references before running prisma migrate dev and then restores the schema.

: '''
This file runs the `prisma migrate dev` command with a workaround for the
current lack of views support.

It tries to solve this problem:
If a database contains views and `prisma introspect` is run on it, Prisma will
not recognize these views. Therefore, when running `prisma migrate dev`,
the views will not be created.

Prisma has a guide on how to handle this:
https://www.prisma.io/docs/guides/general-guides/database-workflows/sql-views-postgres.

Unfortunately, this introduces some headache when using `prisma migrate dev`
from now on: Prisma will try to create these manually added models as relations
which fails because they already exist as views.

To workaround this, every manually created model for a view should be annotated
with "/// @view".
The script backups the current schema under `schema.prisma.backup` and then
modifies the `schema.prisma` file by deleting these annotated models including
their references. Afterwards, the file is restored and `prisma generate` is
called to generate the Prisma client with these view models included.
'''

SCHEMA=prisma/schema.prisma
BACKUP=prisma/schema.prisma.backup
ANNOTATION="/// @view"

cp "$SCHEMA" "$BACKUP"
echo "Created backup for $SCHEMA at $BACKUP"

echo -n "Detecting view models ... "
view_models=$(grep "$ANNOTATION" -A 1 "$SCHEMA" | grep -P "(?<=model )[a-zA-Z]+" -o)
echo "Done"
echo "Detected view models: $view_models"  | tr '\n' ' '

echo -n "Deleting view model references ... "
for model in $view_models; do
  sed -i "/$model/d" "$SCHEMA"
done
echo "Done"

echo -n "Deleting view models ... "
sed -i "/${ANNOTATION//\//\\/}/,/}/d" "$SCHEMA"
echo "Done"

echo 'Running `prisma migrate dev` ... '
npx prisma migrate dev
echo 'Running `prisma migrate dev` ... Done'

echo 'Restoring backup and running `npx prisma generate` ... '
mv "$BACKUP" "$SCHEMA"
npx prisma generate
echo 'Restoring backup and running `npx prisma generate` ... Done'

I thought I put this here since this may help someone until Prisma properly supports database views.

ekzyis avatar Apr 05 '21 12:04 ekzyis

I created a script to workaround this issue.

Thanks, had the same idea, but i'm too lazy)

sibeliuz avatar Apr 07 '21 14:04 sibeliuz

Haha, you're welcome :D

I have noticed that my script does not work in the Gitlab CI because the grep in busybox does not include the perl regex option -P.

So I am actually using this line here:

view_models=$(grep "$ANNOTATION" -A 1 "$SCHEMA" | grep "model" | cut -d' ' -f2)

instead of

view_models=$(grep "$ANNOTATION" -A 1 "$SCHEMA" | grep -P "(?<=model )[a-zA-Z]+" -o)

Maybe you or anyone else will stumble across this too :D

ekzyis avatar Apr 07 '21 18:04 ekzyis

I followed the steps found in the docs here: https://www.prisma.io/docs/guides/database-workflows/sql-views-postgres

This doesn't support views which leverage two tables.

SELECT vendor .VendorName, vendor .VendorUno, COUNT(invtran.InvoiceNumber) [Invoices], vendor .Address1, vendor .Address2, vendor .City, MAX(invtran.InvoicePaidDate) [LastPayment], SUM(invtran.InvoiceAmount) [TotalInvoiceAmount] FROM dbo. Vendor vendor LEFT JOIN dbo.InvoiceTransaction invtran ON vendor .VendorUno = invtran.VendorUno

ChipClark avatar Apr 12 '21 20:04 ChipClark

Why not? What schema are you trying for that @ChipClark and what error message are you getting with that?

janpio avatar Apr 12 '21 21:04 janpio

COUNT, MAX, SUM do not exist in the current table.

ChipClark avatar Apr 12 '21 22:04 ChipClark