OMG. I just found this.
These guys apparently think their new ORM with a bunch of not-implemented-yet features to handle specific use cases and a philosophy of delegating responsibility for essential data integrity requirements to application code is better than tried-and-tested, decades-of-track-record ACID transactions implemented by the major database engines, because of some vague waffle about modern, scalable, serverless something-or-other.
Well, that was the shortest evaluation of a database library I've ever been part of. Thanks for the heads-up, you probably just saved us several days of wasted time.
Hello!
I’ve been using Prisma https://www.prisma.io and I’m happy with it. The downside is that it doesn’t support as many databases as Sequelize.
I use it with blitzjs https://blitzjs.com it’s a full framework that uses Prisma as their ORM
MikroORM seems like the spiritual successor to TypeORM, people seem to love it. https://mikro-orm.io/
For a different direction, there’s Prisma. A lot of people love it and they do a ton of developer outreach. I bet someone from the company that makes it will show up to comment now that their name has been mentioned. They released a schema migration tool sometime in the last six months that looks amazing and would probably convince me to give it a go if I was starting a new project. https://www.prisma.io/
I just started using Prisma and absolutely love it. One thing that irks me is the Typescript support for relationships. For example, if I have Model A that is 1:m with Model B, the generated type for A doesn’t have the relationship to B.
There is a workaround (https://www.prisma.io/docs/concepts/components/prisma-schema/relations) but that makes it hard to actually use the types. For example, if I get a single row of Model A through the Prisma client and include the associated Model Bs, the returned type is the default type (no Model B association). If I extend the type with a validator to include the Model B associations, I can’t use that type (with association) because the client returns to the default type (no association).
I can post a code example of this but the docs explain it pretty well. I may be missing something. But otherwise I love Prisma 😊
Please refer this article its explain in details about each ORMs. First read, thank me later ;)
I'm not sure how you're learning GraphQL, but it seems like Prisma might solve a lot of your problems: https://www.prisma.io/
It creates the database modeling and queries for you so you don't have to write SQL queries.
I believe nexus has an example of what you want, a client generated against a schema.
​
In general I am against code-first on the backend and disagree with some things Nexus mentions in their article, and for the frontend I use graphql-code-generator against client queries written in GraphQL (which avoids some of the repetitiveness you've mentioned). Using the more flexible GraphQL language enables things like fragments, directives, and multiple sub-operations.
​
To be fair there could eventually be code-first solutions for those things, but I don't see enough reason to not just use GraphQL. That first level of wrapping you mentioned is similar to function wrapping in base JS/TS and has use once queries are less simple.
​
I would also argue that your example is more verbose since the types need to be manually written (but nexus clients can do that for you for simple operations).
Sure about that I am using prisma client which from their documentation at Connecting and Disconnecting from DB they say it handles automatically every connection, It creates a pool and disconnects from it when the process ends. SO i think that isn't a bottleneck
You can read about the issues here. At the end it mentions that using using PgBouncer prevents your application from exhausting the database's connection limit. If you use Supabase for your Postgres database, it comes with PgBouncer for free.
What is the error you're getting? If no error, what is the state of the database after running that code? Also, try enabling Prisma's debug mode
Hey there, I wrote the TypeORM comparison page you've shared. First, great to hear that it did help convince you to use Prisma! Second, it definitely wasn't my intention to diminish TypeORM – so I'd love to learn if there were specific parts on that page that felt like they were degrading TypeORM. If that's the case, I'll make an effort to improve these!
Working at Prisma, I obviously want our tools to succeed and am personally convinced that Prisma is the best tool for most use cases application developers have. However, it is definitely not my intention to depreciate other tools along the way but rather want to help people get a good overview of the capabilities of each!
Nikolas from the Prisma team here!
Prisma is definitely ripe to be used in large-scale projects! :) In fact, we're currently putting together some info about companies that are using Prisma in production.
Also, we have a Prisma Enterprise Event coming up in a few weeks, that you can join for free if you want to learn more about using Prisma at scale.
Finally, I can recommend these two articles for further reading:
https://www.prisma.io/blog/prisma-2-is-coming-soon-mwwfhevie993
> TLDR >Prisma 2 will introduce fundamental improvements: >Enabling usage of Prisma as a library without the need for the Prisma server. >Making Prisma workflows (access, migrate, manage) available as standalone tools. >Providing a stable foundation for fewer breaking changes and more flexibility.
Blog article explaining Prisma
Comparison of Hasura (similar tool) vs Prisma, note that this is written by the Hasura team, so it does come off lopsided.
I haven't used either tool but am interested to see how the community will like Prisma 2.
PostgreSQL does not support filtering on the key value of an object inside an array yet. (AFAIK)
Hey there, Nikolas from the Prisma team here! I'm obviously biased but I definitely believe is a great ORM to pick for your applications.
To help you decide, maybe check out this comparison in our docs. Also, this article written by one of our community members might be interesting for you to check out: Migrating a Large Production App From TypeORM To Prisma .
And once you are decided, we even have a migration guide in our docs that helps you move from TypeORM to Prisma :)
It sounds like you want to configure referential actions in your schema such that the delete of associated rows in other tables happen automatically. I don’t know how to do it with Seqalize, but it is super easy in Prisma https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions
I've been studying NextJS lately as well. And, as far as I understand, NextJs is opinionated about a lot of stuff, but not how your backend should work.
I'd say that NextJS works better when there is a backend separated from the frontend, even though there is an API feature in Next.
In case you still want to use the backend in next, take a look on the Prisma project
Reference: https://www.prisma.io/nextjs
Hey there 👋,
You can actually have both automatic migration and SQL migration files with Prisma Migrate.
Prisma Migrate addresses the challenges you mentioned by automatically generating SQL migrations for you, while still giving you the ability to edit the generated SQL prior to execution. (Similar to Django's makemigrations)
By doing so, Prisma Migrate saves you a lot of time creating the migrations while still giving you the final say of how they're executed (so no weird surprises when migrating production)
It comes with different workflows for development and production. So in development, you can easily reset your database and re-execute all the migrations to ensure that the final state is correct. Once you're confident, you typically use the production workflow to only apply the unapplied migrations.
Disclaimer: I work at Prisma. Happy to answer any questions you might have.
TBH, I started with using pg-promise and I just never felt like I needed much else.
It feels really really weird to constantly see libs like TypeORM and Prisma recommended around the NodeJS community, when it feels like these are full of issues and missing features - that are not "bugs" or things that are just not there yet, but actual design decisions.
For some examples:
- https://github.com/typeorm/typeorm/issues/3416
- https://www.prisma.io/docs/about/limitations#long-running-transactions
From this point of view, pg-promise simply always offers a very good safe, stable option that includes "all of sql" + adds some helpers etc. It is IMO in that perfect "lowest level you actually need" spot, where you don't need to bother with implementing application side connection pooling etc.
I recommend you look at the documentation, github and stackoverflow for pg-promise and then compare that with other libraries (seriously, look at the author of pretty much every accepted answer on stackoverflow).
I also recommend that you check slonik out (https://github.com/gajus/slonik#how-are-they-different). I do not have any production experience with it but it seems to be very close to what pg-promise is.
So my list of things worth checking out (things for which I have not yet come across dealbreakers like the aforementioned ones):
- pg promise / slonik for an actual "lower level" sql client (both based on pg which is the base driver)
- knex.js / objection.js for query building
- MikroORM for an orm
Out of all of those I only have production (as in billions of rows, TPS in multiple thousands) experience using pg-promise so if anyone (or you) has some additional info for the others please do share.
The generator is modular. You can write your own generator plugin or use one of the community ones if they suit you.
Thanks for sharing that link. They did a great job of motivating us to accept that transactions are problematic. The reasons: (1) they're hard to use in serverless function settings, and (2) some databases falsely claim to be ACID or something and somehow that's a problem for transactions in every database? I don't know.
Prisma has left me unimpressed in the past, and that continues today. From https://www.prisma.io/blog/prisma-and-graphql-mfl5y2r7t49c:
What developers should care about is the Prisma client API!
For me, that's a great anti-sales pitch. These days I'm diving into the database with two feet, and the last thing I want to do is separate myself from its powerful features. That philosophy of Prisma's seems to be pretty central (https://www.prisma.io/docs/concepts/overview/why-prisma#application-developers-should-care-about-data--not-sql):
> After all, developers should only care about the data they need to implement a feature and not spend time figuring out complicated SQL queries or massaging query results to fit their needs.
And this confusing claim from that same link:
> Developers should be able to ask for the data they need instead of
having to worry about "doing the right thing" in their SQL queries.
SQL precisely is for asking for the data I need!
IIRC, they implement their own transaction flow that sits separately from standard SQL transactions. I think it's okay for most situations, but relying on an application-level library to handle what many consider to be a database constraint is a hard sell to some.
https://www.prisma.io/blog/how-prisma-supports-transactions-x45s1d5l0ww1
Here is a nice tutorial about pagination in prisma. https://www.prisma.io/docs/concepts/components/prisma-client/pagination
So you basicly have to define a state for skip and take or hard code the take. It depends on your situation. If you show how your code looks I can show you how to implement it.
It's an ORM that's pretty good at building GraphQL and REST APIs: https://www.prisma.io/
It does a lot of the grunt work for you like generating database create/read/update/delete methods for all your data types so you just focus on writing the endpoints or resolvers instead.
I don't mind at all! I'm using Prisma as the ORM layer, it essentially turns my database into a GraphQL API. It was a game changer I've used from the start, and has vastly accelerated my development. I'm not writing raw queries to the DB, rather I'm using Prisma's generated API to access the data. As my models/schema change, the API is automatically updated. It's absolutely wild that it exists, but man it's the best.
Also, the rise of serverless tech and services has also helped a lot. I run my backend as serverless microservices. This takes the weight of a lot of dev ops off my shoulders, and also makes the backend super scalable.
Not sure how much detail you were looking for, but I hope this helped!
Good question.
Sqlmancer is similar to Prisma, in that it generates a type-safe database client for you that can then be used inside your resolvers. Prisma requires you to define your database models separately from your schema, while Sqlmancer relies directly on your type definitions.
Prisma 2 no longer supports schema delegation or GraphQL binding, so you can't just pass along your query and have it automagically work with the client. Sqlmancer allows you to pass in the GraphQLResolveInfo object passed to your resolver and it uses that to build the SQL query. Maybe u/nikolasburk can correct me here, but as I understand it, the only way to do bind your schema to your Prisma models like that is to use Nexus and its Prisma plugin.
Prisma 2 interacts with the database through its own query engine binary. Sqlmancer, on the other hand, relies on existing driver libraries like pg
and mysql2
. As a result, Sqlmancer is a bit less restrictive in what it can do. For example, it supports long-running transactions, which Prisma doesn't.
Since Hasura is not a library but more of an out-of-the-box solution, it's a bit harder to compare the two. In terms of querying capabilities, once Sqlmancer supports aggregate queries, it should be somewhat more robust than Hasura (for example, it already supports filtering and sorting by a relation's aggregated values). Hasura also currently only works with Postgres, while Sqlmancer will minimally support MariaDB and MySql as well by the time it hits beta.
These comparisons are based on my only rough familiarity with the two solutions. My apologies to both Hasura's and Prisma's teams if I misrepresented anything in the comments above.
I will suggest you to use Prisma, that will simplify things for you. You will not have to handle schema part of the SQL/NoSQL DB that you intend to use, prisma itself takes care of that.
The equivalent for the above SQL table in prisma would be something like:
​
type Ticket {
id: ID! @unique @id
status: Integer!
}
​
type Event {
id: ID! @unique @id
ticket: Ticket! @relation(link: INLINE)
status: Integer!
}
​
@unique
suggests that it has to be unique
@id
makes it primary key identity
!
makes it not null
I've wanted to achieve this as well, and I came up with a solution I think you'll find interesting.
What I do is that I separate my app logic into components (ticketing and gamification). Each component has its own executableSchema
and resolver context. Each component can also add things into the context, which will be available for the rest of them.
From here, I stitch these schemas together using Apollo server and connect them using the extend
feature of the SDL. Let's pretend we have a User schema and a Thread schema in a Javascript app. They can fully function separately, since they're both executableSchema
s. I'd stitch them like this: https://i.imgur.com/S8aRc3s.png
This way, all your schemas are completely separate, they function independently, but work together in one app. You can also take a component and copy it into another app if you want to.
Of course then you need to add a resolver for the createdBy
field that resolves from userSchema
, but it feels natural to the idea of GraphQL. You can even integrate remote APIs this way!
well, prisma deploy will generate the client (bindings) but to get the auto generated schema (.graphql file) for the service you need to run this:
​
graphql get-schema --endpoint $PRISMA_ENDPOINT --output prisma.graphql --no-all
​
It's all laid out in the docs: https://www.prisma.io/docs/data-model-and-migrations/data-model-knul/
Yeah I'll have to check it out. I only just recently discovered that postgraphile isn't the only one, only one I've tried so far though. Also came across https://www.prisma.io/ - not sure how it differs from the other two.
Cool to see that this way of doing things is gaining some traction overall.
I've even started to wonder if it makes sense to just use graphql to query my databases from the backend too. i.e. Instead of using a regular SQL ORM.
I guess it would be slower, but wondering if there's other disadvantages.
I guess it would need a graphql client that can hydrate your models.
I'm using TypeORM for my normal DB queries on the backend, I think either way, I'll still add a saveViaGraphql() method to my base model class so that I can use my regular models on the backend and communicate with remote DBs without opening ports or needing VPN etc. That was the initial thought that got me wondering if it makes sense to just use graphql for everything. I'm sure there would be some downsides though.
Looking into it made me even more confused about the whole thing for a while. You are right. For anybody else there is some good info here about the differences between the two.
If your db is postgres or mysql and db schema will be generated from code as well, look into Prisma.
It generates db schemas (can import existing one as well) and offers a graphql API over the data.
The draw back, as it is not meant to be exposed to outside, is that security options are extremely limited right now.
Your situation is super common - and the prime use case for GraphQL Bindings. Basically you are using bindings to connect to an existing GraphQL API and reuse it to define a new GraphQL API.
Here's a simple example. Let's say you only want to expose a feed
field that exposes all published posts. Then you can use the posts
query exposed by the Prisma Binding like so:
feed(parent, args, ctx, info) { return ctx.db.query.posts({ where: { isPublished: true } }, info) },
In this code snippet, ctx.db
relates to the Prisma Binding, and with ctx.db.query.posts
we can access the posts
query.
Now you can easily add authentication logic. Let's say only logged-in users can see the feed - so let's add a check before returning the feed!
feed(parent, args, ctx, info) { if (!isAuthenticated(ctx)) { throw new Error('Not authenticated!') }
return ctx.db.query.posts({ where: { isPublished: true } }, info) },
You can find a complete example for this entire setup here.
I've been using Prisma for a few years now, it has one of the best developer experiences in my opinion. I've used typeORM in the past but it took me a while for it to click and I truly understand how to make complex relations and all. With Prisma it all just fells very straight forward, I might be little biased since I became a Prisma ambassador a few months ago, but I believe it's more than worth the try, the features are very useful and the learning curve is very low. If you want to see how simple it can be to deal with complex table relations, I made a talk about it a while ago.
What is the query your using to get the data.
With prisma you have to do
const getUser = await prisma.user.findUnique({
where: {
id: "20",
},
include: {
info: true, // All posts where authorId == 20
},
});
After the where clause you need to specify that you want the info relationship by adding it to include. This is because relationships with posts arent actually stored in the database prisma will fetch the relationships when you tell it to include them.
​
You can read up on it here https://www.prisma.io/docs/concepts/components/prisma-schema/relations. The only thing I'm unsure about is that you use @@map() I've never used that and I'm not sure if that's supposed to replace the include and automatically fetch the relationships. If it is then you can ignore my post.
Yes you have it correct
You can store SQL in version control. I think what you are looking for here is a concept called "Migrations" that allow you to alter the schema and objects in the database and roll those changes upward. https://www.prisma.io/dataguide/types/relational/what-are-database-migrations
Redshift is a Data Warehouse database managed through AWS and likely is beyond the scope of your needs.
If it's really going to hold just 50 products max, I'd suggest learning SQLite, it's dead simple to get started with and built in to many platforms (Android for example.) Otherwise, MongoDB with Mongoose is also easy to get started with and easy to deploy with Mongo Atlas.
Firestore is in no terms bad, but gets expensive as you scale and has a vendor lock element to it. For a simple project though, I suppose it would be fine as Firebases Authentication service is one of the best out there, you'll probably need some authentication and not having to built it from scratch is nice.
For a SQL database, PostreSQL has a learning curve to it, but it's one of the best SQL databases out there and definitely something you'll want to learn some day. Prisma has great support for it.
Have to say, the question is almost frighteningly vague.
Have you made any decisions whatsoever regarding your stack? Is the project truly just an idea at this time or have you started on any aspect of it?
Speaking in API specifically.. I mean that’s.. yeah that’s a weird question. Are you asking about what backend tech to use? But you also mention persisting data… are you asking about which database architecture?
All questions for clarity aside, I will say that I’m currently working on my second ‘full stack’ project and I never finished my first one. What I’m using right now is Sveltekit with an SQLite database managed by Prisma for an ORM. I have to say it’s marvelous. Absolutely a dream, everything is coming together with very little effort (on the backend anyway, getting too picky with the UI).
ORMs exist so it's much easier (and safer) for devs to start using a DB.
You don't need to be fluent in SQL to start working with a DB, just use whatever functions the ORM provides.
All ORMs have some limitations compared with just using native SQL, but in the brighter side they offer simplicity, so you can get going quickly. This way, you might be truly using one language to do it all: your front-end, your back-end and your DB access.
Depending on the DB, some add extra utilities, like hooks or payload validation and TS types to make the job even easier.
Only problem with working with data is that oftentimes you need to declare you model a few times: one for the REST request, another for the validation, and another for the DB itself. A ORM can help you minimize that.
Plus it can help configuring your DB in whatever enviroment you are. If you are in a development enviroment, just set the DB with the development credentials and seed some fake data into it, so you can add testing to your DB. This is particularily useful when you want to deploy the project and seek near 100% coverage.
Furthermore, if you want to create, say a GraphQL interface, you need to add yet another data definition to the workload. A ORM might help you with that too to make it more fluent. (https://www.prisma.io/graphql).
So in summary, an ORM is mostly how a developer approaches SQL without having to learn and master yet another language, plus it gives extra features so make you code more complete and safe than just using barebones approaches.
They are not perfect as many of them are work in progress. So you need to evaluate their pros and cons carefully. Prisma is one of the most solid ones, with the caveat that your schemas must all live in just one file. Not a biggie.
https://www.prisma.io/docs/concepts/database-connectors/mongodb#known-limitations it felt like the limitations are just so big that it just didn't make sense to bring it up. Besides, Prisma feels just like a layer over a database to use it in GraphQL style. I personally dislike this approach as it will limit you very fast. Do you expose prisma directly to your clients? How do you handle complex security logic for certain actions?
Hey there,
Daniel from the Prisma team here.
Prisma has been production-ready since April this year and we've heard from thousands of developers who've successfully deployed Prisma to production.
Is there a specific stability problem you have come across that perhaps I can speak to?
> like changing their npm install route
Can you be more specific about what you mean?
If you have any questions I'd be happy to answer.
One alternative not mentioned yet is to use getServerSideProps. You can see a comparison of the different options here: https://www.prisma.io/nextjs
​
Prisma also has experimental support for React Server Components: https://www.prisma.io/react-server-components
yes I tried, and I agree it's most pleasant to work with in terms of typescript support.
but I'd not pick prisma for real projects because of limitations, too long to discuss what parts are actually missed, in this place they officially claim that prisma gives you less control over database, that's a fact: https://www.prisma.io/docs/concepts/overview/why-prisma
in other discussions of prisma here on reddit someone said they are using combo of prisma + something else for full control
Hey there, Nikolas from Prisma here! Thanks for highlighting our TypeScript integration, this part is definitely something that we're really proud :) albeit it should be noted that many of the benefits of TS are even available when developing with plain JavaScript (e.g. the auto-completing DB queries with Prisma Client).
> still has some major bugs and lacking some features you would expect an orm to have.
Could you maybe elaborate a bit on the major bugs you're seeing at Prisma? We have a biweekly release process on GitHub and are usually very quick to react to any bugs that might make it into a release by issuing patch releases. I'm not aware of any critical bugs in our stable tooling (i.e. anything that has been released under "General Availability"), but if you find something it would be super helpful if you could open an issue on GitHub so that we can address it as fast as possible.
Also, what are the features you're missing from Prisma that you would expect an ORM to have? :)
Prisma does provide some of its own mitigations for the n+1 problem: https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance
From the ones I've named, I'd pick either TypeORM or Prisma. The getting started guides for these are straight forward and their documentation is a bit more on the friendlier side of things.
If you aren't using one, how are you saving whether or not a user has certain commands enabled or disabled (such that restarting your bot doesn't get rid of the settings)? I assume you aren't.
That's the point of the example tasks I listed.
I'd seriously recommend giving these tasks a go as they will help you build some very relevant foundational skills for programming in general.
i think the documentation is very good, here is findMany for example. you can find more about filtering here. you have to deal with null values though, prisma won’t figure out your intent, searching for data where one nullable field is null is a valid case too, so prisma won’t just ignore that.
Thanks for sharing.
To those looking to add a database to the project, check out Prisma and how it works with Next.js: https://www.prisma.io/nextjs
Prisma supports PostgreSQL, MySQL, SQL Server, SQLite, and MongoDB (Preview).
I'd recommend you use version 6 of Sequelize - the guide already suggests to use 5+ as 4 has a security vulnerability. Alternatively I'd recommend you use Prisma instead!
For folder structure, it's pretty much up to you, as long as your imports and requires are what they need to be.
database
folder, in there create the dbInit.js
, dbObjects.jsand
models` folder.If you extend the client class and give it a db
property, you can assign the Sequelize instance to it and then access your db with this.client.db
throughout.
The guide is using v4 which is outdated, I'm also a fan of the class based approach with Sequelize, this involves extending the Model class, passing in your options to the super constructor, and overriding the built in functions to setup associations, filters, etc. Unfortunately the documentation isn't that great - it's extensive and exhaustive, but it's hard to navigate and understand if you don't already know what you're looking at.
Hey there,
Daniel from the Prisma team here.
There are a number of frameworks that use Prisma out of the box, and your choice will depend on whether you want a full-stack framework that also covers the frontend or just a backend framework.
Prisma itself makes your interactions with the database easier with full type-safety for all your queries. You can use it with any framework or Node.js technology of your choice.
Some frameworks worth looking at if you are going down the full-stack route: - https://blitzjs.com/ - https://redwoodjs.com/ - https://www.prisma.io/nextjs
I'd be happy to answer any questions 🙌
To understand the problem with serverless & database connections have a look at the Prisma docs: https://www.prisma.io/docs/guides/performance-and-optimization/connection-management#the-serverless-challenge it has examples with Prisma, but it applies to basically every DB
Tl;dr: You need to make sure that a serverless function doesn't instantiate a new connection. For MYSQL, there is serverless-mysql. I don't have experience with MongoDB sadly, but the caching seems to be on the right track.
Hey there,
Daniel from the Prisma team here.
With Prisma, defining such relations is done with the Prisma schema:
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
created DateTime @default(now())
title String @db.VarChar(70)
content String
author User? @relation(fields: [authorId], references: [id])
authorId Int
}
The schema defines a 1:n relation between User
and Post
. To create the database schema you can use the following command:
prisma db push
And you should be able to start querying the database.
For a more extensive overview, check out our getting started guide
Hey, Tasin from Prisma here with a quick update.
We're really excited to announce that Interactive Transactions (formerly known as Long-Running Transactions) has been released in Prisma Version 2.29.0. For now, the feature is still in Preview, and it will be released as Generally Available in the coming months.
This is perhaps what you meant when talking about standard SQL Transactions (Run any arbitrary sync/async code in the middle of a transaction and roll back in case of errors).
Happy to answer any questions you might have about this!
Hey, I'm Tasin from Prisma with a update.
We're really excited to announce that Interactive Transactions (formerly known as Long-Running Transactions) has been released in Prisma Version 2.29.0. For now, the feature is still in Preview, and it will be released as Generally Available in the coming months.
I started building out a new version of my own site a few months back in Next.js, but wound up pivoting to GatsbyJS after a while because I really needed an abstraction over the Markdown files I was using for the content and GraphQL worked a treat for that - using Markdown directly in Next.js was a lot more grief.
I really like React.js and use it all the time, and I recently started using Typescript with it after years of sticking with Flow. I actually really like Next.js and would use it again, it just wasn't a good fit for a Markdown powered site. I'd consider using it again in future if I wanted something with a database, but I'd be sure to use Typescript and I'd use https://www.prisma.io/ for the ORM.
;(
nope, I try with findFirst and findMany (findOne seem to be an old function... not valid in my env)
https://www.prisma.io/docs/concepts/components/prisma-client/crud#findone
same error :
Unknown field \
role` for select statement on model User. Available options are listed in green. Did you mean `name`?`
Unknown field \
sites` for select statement on model User. Available options are listed in green. Did you mean `id`?`
Hey there, Daniel from the Prisma team here.
> Can you clarify to me the distinction you are making between using Prisma and GraphQL vs NestJS?
Prisma Client is what you would use in order to access the database in Node.js with all the type-safety bells and whistles.
You can use Prisma to build REST APIs with any Node.js HTTP framework, e.g. NestJS, Fastify, Express, and Hapi.
Similarly, you can also build a GraphQL schema with Prisma and any GraphQL framework (TypeGraphQL, NestJS, Nexus, SDL-first). Once your GraphQL schema is constructed, you can create the API with any HTTP framework supporting GraphQL.
NestJS helps you with both the GraphQL schema construction and HTTP request handling.
I think you might find the following resources helpful: - https://www.prisma.io/graphql - https://github.com/prisma/prisma-examples/tree/latest/typescript
Yes, you'll have the same issue. findUnique
is just more efficient and was made for fetching a single record. You can learn more about it in the docs
Hey there,
Daniel from the Prisma team here.
When it comes to building a GraphQL API with Prisma there are a bunch of decisions to make: - How do you define the GraphQL schema: SDL-first or code-first approach, e.g. TypeGraphQL and Nexus. - How you define the resolvers: TypeGraphQL comes with Prisma integration which will generate the resolvers for you. With Nexus and nexus-plugin-prisma you can project your Prisma model types to build your GraphQL schema but still have to define your resolvers manually. - HTTP GraphQL Server: Apollo Server and Mercurius
You can learn more and find different examples here: https://www.prisma.io/docs/concepts/overview/prisma-in-your-stack/graphql
Happy to answer any questions!
I'm running the migrations by invoking the Prisma CLI from execFileSync
, programmatically. It's not ideal, but it works. Running migrate
automatically applies the seed file. When auto-migrate is disabled, I just run the seed file after the app starts.
> Why wouldn't you give the user full control of the api? Is it a limitation of the Rust web-server/graphql architecture?
That's definitely a good intuition. While not technically impossible, it would be certainly quite a bit of work to implement long-running transactions (LRTs). We don't categorically exclude ever bringing LRTs to the Prisma Client API though – but because it's a technically more challenging and time-consuming feature, we really want to make sure it'd be worth it in the end. And right now we rather feel like the value it would provide doesn't justify the investment. Plus, as I mentioned, we want to build Prisma in a way that it's compatible with modern deployment models, so that's another strong reason why we're not compelled to implement LRTs in Prisma right now.
> My main use case for long running transactions is running business logic between operations so I can calculate the next one.
That's fair. This is definitely a valid use case and one that Prisma can't solve natively at the moment! If this is a major blocker for you and you can't afford to work around this (e.g. by using a DB driver or a query builder like knex.js), then Prisma might not the be the right choice for you. That's unfortunate but we also don't believe that Prisma has to fit every application. It certainly has its strong suits and for many developers the limitations are not that problematic, but if Prisma doesn't provide what you need it's absolutely fair to choose a different tool :)
Great to hear u/MuchStark! This particular issue is always about your db setup, so it's good to know what it expects. You should definitely check what type of integer or string is used, since pisma mutation creates very limited Int by default. However you can change it to any data type you want and that's awesome, even though migrations are still marked as experimental. See https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#native-types-mapping
Most ORMs come with a connection pool to the database. This allows the ORM to limit the number of its connections to the database (and avoid exhausting PostgreSQL's connection limit) and funnel queries to the DBs based on the number of unused DB connections in the ORM's connection pool.
The first thing to check is the connection limit of your database and then set that in the ORM connection configuration.
I couldn't find the specific configuration for PostgreSQL in TypeORM (though for MSSQL you can set the pool.max
), however in Prisma this is configurable via connection_limit
parameter in the database connection URL.
I'll answer the last question first because there the answer is most clear :D
> Can you use Prisma Client without Prisma Migrate?
Absolutely! Nobody forces you to sue Prisma Migrate to make changes to your schema with Prisma. You can just keep running your knex migrations and then introspect your database to generate your Prisma models. The primary use case for introspection is folks getting started with an existing database, but I also know of some people that like you prefer to run their own migrations and keep introspecting the DB after a schema change.
> Can you still use "my" approach with Prisma Client?
Sorry, I missed what exactly you mean with "your" approach. Do you mean keeping the deltas of your schema changes in a migration history or what exactly are you referring to?
> Can you use raw SQL with Prisma Migrate ?
Prisma Migrate also generates SQL migration files that you can customize as much as you want. So yes, whatever schema change you'd like to perform with raw SQL, you can do it with Prisma Migrate as well. Does that answer your question?
Prisma Client is the "query builder" component of Prisma – it's higher level than traditional SQL query builders though. For JOINs, it provides the select
and include
options that you can pass to your queries. Here's an example for using it with include
:
const allUsersWithPosts = await prisma.user.findMany({ include: { posts: true }, })
What's really nice about this is that that the result is fully typed to this:
const allUsersWithPosts: (User & { posts: Post[]; })[]
Where User
and Post
look as follows (these types are generated
by Prisma):
export type User = { id: number email: string name: string | null }
export type Post = { id: number title: string content: string | null published: boolean authorId: number | null }
You can check out the Prisma Client docs to learn more :)
Love this perspective, big plus one! It's a tradeoff between productivity and control. But nobody forces you to write all your queries using the ORM, you can (and should) drop down to raw SQL when needed and still get the productivity benefits for the majority of your queries.
I've recently started learning backend after being frontend for a long time, here's some tips:
If you want to learn how to make an API without writing a minimal amount of SQL I can't recommend Prisma enough. Prisma allows you to abstract a lot of SQL queries into simple prisma.users.fetchAll()
statements while still giving you the ability to use SQL for more complex queries.
It also has a ton of examples which you can learn from, which you may want because:
Prisma was a good stepping stone for me, it's a great learning tool with a lot of scalability.
It will work, but not always. I work with PostgreSQL, and there are specific rules for using single and double quotes within the queries themselves. So not having to use quotes to delimite the query gives you the freedom to use both single AND souble quotes inside the query as needed. cfr. https://www.prisma.io/dataguide/postgresql/short-guides/quoting-rules
Agree with this! You might also want to check out this ORM comparison to learn more about the different choices besides MikroORM :)
Check out this library: https://paljs.com/plugins/select
It uses Prisma and not TypeORM but it does exactly what you're looking for: Extracting the requested fields from the <code>info</code> object and ensures only these fields are being retrieved from the database.
Hey there, Nikolas from the Prisma team here! This error happens when you're using a DB server where you don't have access rights to create a new database.
These access rights are needed because Prisma Migrate uses a shadow database when a migration is performed.
We already have an open issue for this problem here: https://github.com/prisma/prisma/issues/4571
Hey there, cascasing deletes are not usable via the Prisma schema but there are two ways to work around this:
With the second approach, you can configure cascading deletes in your Prisma schema as follows:
model User { id Int @default(autoincrement()) @id createdAt DateTime @default(now()) email String @unique name String? password String /// @onDelete(CASCADE) posts Post[] group Group? @relation(fields: [groupId], references: [id]) groupId Int? /// @onDelete(SET_NULL) comments Comment[] }
model Post { id Int @default(autoincrement()) @id published Boolean @default(false) title String author User? @relation(fields: [authorId], references: [id]) authorId Int? /// @onDelete(CASCADE) comments Comment[] createdAt DateTime @default(now()) updatedAt DateTime @updatedAt }
model Comment { id Int @default(autoincrement()) @id contain String post Post @relation(fields: [postId], references: [id]) postId Int author User? @relation(fields: [authorId], references: [id]) authorId Int? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt }
model Group { id Int @default(autoincrement()) @id name String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt /// @onDelete(SET_NULL) users User[] }
> I couldn't understand the example of pinning together prisma + graphQL
Which example do you refer to exactly and what was not clear? I'm happy to help you with that!
Maybe this page helps understand a bit better how Prisma and GraphQL fit together: https://www.prisma.io/graphql
Generally, Prisma is used just like any other ORM in your GraphQL resolvers. Depending on the GraphQL library you use, there might be additional integrations that you can use e.g. to expose your Prisma models via GraphQL or generate CRUD operations.
At the moment, I'm aware of integrations for Nexus and TypeGraphQL.
Hey there! I just wanted to drop in and ask whether you had considered Prisma as an ORM alternative to migrate to as well? If you care about type safety, then I think you'll really enjoy working with Prisma (TypeScript is a first-class citizen in Prisma and all your DB queries will be entirely type-safe, even those for where you query for partial models or relations).
If you want to try it out with your existing database, you just need to run a couple of commands until you can query your DB. It also lends itself really well for incremental adoption so that you don't need to migrate your entire code base all at once!
Here's a quick overview for how you'd get started with an existing database (alternatively you can follow this more comprehensive [guide]()https://www.prisma.io/docs/getting-started/setup-prisma/add-to-existing-project-typescript-postgres):
Install the Prisma CLI
npm install @prisma/cli --save-dev
Initialize Prisma
npx prisma init
Set your database connection connection URL via an env var or directly in the generated Prisma schema file
Introspect your database
npx prisma introspect
Install Prisma Client (which allows you to query your DB via TypeScript)
npm install @prisma/client
Start querying your DB, e.g.:
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
// the queries are tailored to your DB schema const users = await prisma.user.findMany()
I'd love to hear what you think of Prisma as an ORM alternative :)
Quick question on Prisma.
I was reading through the docs and it says to create a schema file which contains CREATE TABLEs.
My question is: what if I've already got a database setup with tables?
Or are we just doing that so Prisma knows how to build the models?
While numerous technical considerations would favor Raw SQL over an ORM, it's worth considering how the choice would affect collaboration when working in a team.
If you're working solo on a project, how comfortable and experienced you are with a given abstraction, i.e., database access library might be the most important one. If you are working in a team, it's worth considering how maintainable it is for a team to be working with raw SQL when there are different levels of SQL competence in your team.
Another important consideration –irrespective of ORM or raw SQL– is type safety. Arguably, this is one of the most important aspects when working with a database because being able to detect type errors for all your queries has several benefits:
I work at Prisma, where we're developing the next generation of database access tools for Node.js and TypeScript, so hopefully, I can share my experiences having worked with relational databases over the last ten years. I also realize that this might sound biased, which is why I'd suggest checking out.
Prisma is a fully type-safe database client that sits somewhere between query builders and ORMs. It also gives you fine control over how relations are fetched and supports raw SQL queries.
Prisma is not alone in this family of database access libraries that focus on TypeSafety. Both PgTyped and Slonik with @slonik/typegen have a similar goal in mind, albeit only with raw SQL support.
Well yeah, it's a Go port of the popular https://www.prisma.io/ for the node ecosystem. And the language and feature-set is super easy to learn.
Is construct SQL only? Could it be extended to work with KV stores such as Bolt or Badger?
Dude, calm down. You assume plenty of wrong tings about me.
That's just not true. Most (if not all) ORMs come with a query builder. Good ORMs let your write directly SQLs for very complicated queries. Most of the times those complicated queries are for reports and a like which ORMs are the wrong tool for. ORMs do not create inefficient. For simple projects, all good
It's quite the contrary. ORMs are too beefy to simple projects and shine particularly in bigger projects. It seems you used terrible ORMs in your experiences to come to that conclusion.
You need in all projects validation and serialization. Stuff Prisma doesn't provide, hence there is no way around writing interface multiple times - which is inefficient.
Prisma generated code, see https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/generating-prisma-client, essentially converting .prisma to JS code. What don't you understand by that?
Sure, that doesn't make the point any less valid.
MongoDB supports inlined joins. However, sometimes (and this is also used to optimize complex and high-performance projects in SQL) it is necessary to NOT join a table inline but do a subsequent query. Both ways of joining relations have their pros and cons. And both ways are supported by MongoDB and all other common RDBMs. What you are trying to imply ("MongoDB relation support is slow") is just not true and show only your lack of experience.
Don't know what you are talking about. I don't hate Prisma nor do I hate VC scene. I have myself couple of startups dealing with VS, so there's definitely nothing wrong with it. However, I just point of the cons of Prisma and lack of advantages. I'm actually a dev with 15 exp in the industry, so your cheap shot regarding junior dev is not exactly correct.
Yes, I'd definitely say the paradigm is different though they are both solving the same problem and can indeed be swapped against each other. You can also run them side-by-side for a while in case you want to adopt Prisma incrementally in your app.
We don't have a specific migration guide for Sequelize yet, but we have this guide that explains how to use Prisma in an existing project. The short story is that you can introspect your database with Prisma, install @prisma/client
in your app, and are ready to query your DB.
You can also watch a brief demo of this workflow in this video series. Would love to hear what you think of Prisma once you tried it :)
From my experience, Sequalize is the most popular option. Pretty much every company I have worked for in the last six years have used it heavily. That being said, whilst simple use cases work well, there are deep-seated bugs around relational mapping and pagination.
My personal recommendation would be Prisma. This is a really modern tool and has some awesome features, such as query batching, auto-generated types and automated migrations. I highly recommend it.
Nikolas from the Prisma team here 👋
I can also confirm that you can use Prisma as an alternative to Sequelize, that's exactly what it's made for :) I'm also happy to answer any follow up questions you might have when diving in! (Feel free to ping me on our public Slack, I', @nikolasburk
there as well).
To get started, I recommend running through the Quickstart and reading the Prisma Introduction.
I work at Prisma and recently gave a talk about this topic ("Making frontend developers fullstack"), maybe there are some bits in there that are helpful for you! :)
At Prisma we're building an open-source database toolkit that comes with a type-safe query builder which you can use as an alternative to low-level SQL and higher-level ORMs (you can read a bit more how Prisma fits into the ecosystem in this docs article).
Have you tried Prisma?
Disclaimer: I work as a Developer Advocate at Prisma.
Prisma is not an ORM, but since you mentioned you're using TypeScript, having your database queries and results automatically typed solves the problems that ORMs attempt to solve (making database access easy and predictable) without introducing many of the downsides and complexities of an ORM.
Prisma isn't the only option; [zapatos)(https://jawj.github.io/zapatos/) follows a similar approach.
They seem to share the idea that developers shouldn't need to sync their application models with the database models manually. Especially when there's tooling to solve the syncing problem.
The info arg will hold anything that has been passed to the query, so if you query on the parent with a customer number, then the child can use what is in the info arg in the resolver.
Give this article a look over. Its all about understanding when and how to use the info arghttps://www.prisma.io/blog/graphql-server-basics-demystifying-the-info-argument-in-graphql-resolvers-6f26249f613a
If you can wait a few more months, then check out Prisma :) (disclaimer: I work for them). We're planning to release a connector for MS SQL Server within the next 3-6 months, you can view the full roadmap here.
It's not specific to netlify at all actually, they just have a partnership that makes integrations super easy! At their core they're just a serverless, distributed data endpoint (which is freaking awesome when you compare it to the pain of having to deal with regions and replication for performant DB access on traditional cloud servers).
To your question about MySQL and PHP: yes, you sure could. But it would actually be less versatile, as you're working with one server (that you have to manage, both the OS, security, networking, webesrver like NGINX or Apache), your database engine, your static PHP version, and the VPS itself on whatever service you're using. There's a lot to manage there and a lot of it is super mundane (good to learn, but mundane). Fauna abstracts out all of that so you're just worried about your data and operations. No one, and I mean no one, likes writing SQL queries (and if they say they do they're lying). It's one of the reasons for the growth of tools like Prisma (check it out - definitely the future).
Do I think you should learn how to at least work with and navigate PHP + SQL? Definitely, you'll come across it in the wild with older projects/products. But one thing at a time, and this will get you in the mindset of working with your data in an off-site-persistent manner without worrying about all the other moving parts.
Also, on future projects I'd recommend not using jQuery. It's an archaic tool now. It was super vital years ago, but between the maturity of vanilla JS and the accessibility of React and Vue, it doesn't have a place in the modern web.
The #1 way to learn something is building something with it.
The biggest hurdle here is: How much Javascript do you know? Cause even with a fairly simple knowledge of Javascript you might be able to jump straight into React and see what you can produce. Hooks have simplified React by a LOT so it's really accessible nowadays.
If you work with Wordpress I suppose you also know at least the basics of Mysql or other databases? I've heard Prisma is pretty good for implementing Mysql in modern Javascript frameworks.
Either way you'll want to:
It really all depends what you want to build, there's dozens of tools that facilitate the process of webdev nowadays.
Feel free to ask me any questions you have.
Hey there! I work at Prisma. We experienced the same confusion and dissatisfaction about the state of DB tooling for TypeScript and we've gone to build a fully type-safe database client that's generated from your database schema.
I actually gave a talk with a thorough introduction to it, also demonstrating how you can use Prisma to build REST and GraphQL APIs. I'd love to hear what you think of Prisma as you're evaluating different tools! :)
Hey there! Thanks a lot for linking the video, I very much enjoyed it :D and I totally agree that the naming discussions around Prisma can be confusing.
Many terms, especially in tech, are ambiguous not always 100% clearly defined. If we look at most ORMs out there, they're characterized by the fact that tables are defined as classes in your programming language. Taking the most popular ORMs across languages as examples, e.g. Active Record (Ruby), Hibernate (Java), SQL Alchemy (Python), Entity Framework (C#), Sequelize (Node.js), TypeORM (TypeScript), I think the mapping of classes to tables is indeed the main thing they all have in common, the actual workflows and data access API might differ.
If you understand ORM more generically though and say: "There's relational data in your SQL database, and there's object-oriented data in your programming language, so there has to be a mapping between the two models. There must an object-relational-mapping (ORM taking place somewhere." This is a totally valid approach as well, but after that logic any software written in an OO language that uses a relational DB uses an ORM, which I don't think many developers who use plain SQL or SQL query builders will agree with. TLDR:
The notion of ORMs is ambiguous and tricky, we've laid out our own perspective here: Is Prisma an ORM?.
To recap: Mapping classes to tables is not at all what Prisma does! Prisma provides a database client that exposes a number of tailored functions for you to read and write data in the database. These functions are generated from a declarative representation of your database schema (called the Prisma schema) and provide a fully type safe way to read and write data in your database.
I'm sorry to ask, but did you watch the talk? It's totally fine if you didn't, I just would love to learn which part in the talk gave you the impression that Prisma is an "API generator"?
> Though, every time I run across Prisma articles, it's inevitably someone using it to expose a GQL API, which blows my mind (not in the WOW way, but in the WTF why way).
I'd love to see some of the articles you're referring to? Are these about Prisma 2.0? For Prisma 1 I guess these kinds of articles make sense, Prisma 2.0 is very different though (hence my preface) which is really just about enabling proper database access (that doesn't have to do anything with your API layer, there's no "API generation" aspect to it).
> So Primsa would be more akin to Hibernate/JPA in the Java world?
Yes, except that it doesn't really fit any of the existing categories for database tools which I explained here. It's higher-level than SQL query builders but it's also not an ORM.
That file comes form a toolkit called Prisma:
https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-schema/prisma-schema-file
If you plan to use Prisma then it seems you should not rename that file.
I'd love to hear your thoughts on Prisma 2.0! :) Did you check it out already? We've put a lot of effort into making TypeScript a first-class citizen in Prisma and really push the boundaries of TypeScript to make your DB queries entirely type safe (even partial queries or when including relations).
You can see an example of this in this demo video.
Thanks for the shouout! We're definitely putting a lot of effort into making all database queries entirely type safe (even partial queries). You can see an example of this in this demo video.
That’s all very nice and I am sure you did an awesome job there, but what pushes you to use PHP over JS/TS or Go?
Code first is indeed more appealing than schema first and other projects like Prisma followed the same path.
I am far from being a GraphQL expert but I personally feel Apollo server is a master piece.
With Strapi or Prisma being around I swore that I will never write CRUD again. Like, what's the point? It's so damn easy to do those jobs nowadays that my time is better utilised solving other problems.
IMO the easier problems have now been automated away. For something to be simple, something else has to be complex. Tools feels like they are getting more and more complicated because we are using more of them to solve problems that are already solved by others. Things that used to take programmer days to code is now an install away. The bar for a Hello World project is now a Todo list. 10 years ago that's not easy.
Thanks a lot, that makes a lot of sense to me! I'll quickly follow up on your points individually as well :)
> Our dB types weren’t consistent and meant we couldn’t leverage a data lake for reporting
I completely understand that this can be a major blocker! As I mentioned before, the only "workaround" right now would be to only use Prisma's auto-generated DB client and not (yet!) its migration system. Native DB type support is coming really soon to the migrations as well though!
> Lack of Federation support
I'm assuming you're referring to "Apollo Federation" here? In that case, it's not quite accurate that Prisma "doesn't support" it. You can certainly implement the resolvers of a federated schema using. In that case, you'd use Prisma's auto-generated DB client to talk to your DB inside the resolver.
> Prisma 2 introduces a variant of Graphql, I believe. We wanted to stick to the standardised version. I could be mistaken in this however as I haven’t done a lot of research into this
I'd love to learn more about what gave you the impression that Prisma 2 introduces a variant of GraphQL! Did you get that impression from the docs or some blog post? Could you point me to that?
Note that Prisma 2 itself is a database toolkit, you can use it to implement any sort of application that uses a database, like a REST API, a gRPC API, or of course a GraphQL API (if it talks to a database).
Aside from building out Prisma, we're also heavily investing into GraphQL Nexus, a [code-first])(https://www.prisma.io/blog/the-problems-of-schema-first-graphql-development-x1mn4cb0tyl3) GraphQL schema construction library. We're also building a "Prisma-plugin" for Nexus, so that you can easily connect your Nexus resolvers to your DB. This gives you a single source of truth for your types and saves tons of boilerplate that would be otherwise needed for the resolvers!
Spring Boot is based on the JVM while Apollo is a NodeJS platform.
As other people suggested, you don’t have to “choose” between them in the sense that they can be used within the same project. However they do need to run on two different micro-services since they use a completely different runtime.
Using Apollo totally makes sense as it eliminates a lot of boilerplate code and lets us focus on designing our API. Tools like Prisma can even automate the API generation.
That said, unless you really are tied to Spring Boot, I recommend switching to a pure NodeJS backend. When it comes to Graphql, you’ll be far better served in the TypeScript/JavaScript ecosystem than in the Java world.
By the way, I think we might know each other in real life. Does my name ring a bell?