Skip to main content
View on YouTube to comment and like!

Syntax Video

Write Raw SQL with Type Safety | Prisma TypedSQL

Chapter 1 0:00

intro

the debate of whether to use raw SQL queries inside of your codebase versus using some sort of om is a long one we've been arguing about this for a very long time and developers have opinions that exist on all sides of the spectrum some people only write raw SQL code some people only like to write omm code but with this new feature called type SQL that was released by Prisma they're promising that you can have the best of both worlds or essentially you can write your SQL code in its own dedicated SQL file and whenever you run Prisma generate it will generate typed functions that you can use inside of your codes and so with this new feature they're promising a better developer experience for those scenarios where you actually do need to drop down to Raw SQL code so in this video I'll show you how we can generate these queries some of the features and also some of the limitations that sounds good to you let's dive in my name is CJ welcome to syntax now this feature was added in version

Chapter 2 0:51

minimum version needed

5.19.18 examp I'm going to be showing today are with postgress but they also support MySQL and sqlite and if you haven't seen it check out episode 839 of syntax where one of the co-creators of Prisma sain was on the podcast with weson Scott where he talked about this new feature but also a lot of other things this is a really great conversation they talked about graphql they dove into serverless databases and hosting it's a really fun exploration of the world of of SQL and and a cool conversation to listen to so definitely check it out if you haven't heard it yet so for our examples here I built a simple little blog that has posts from all of the synta taxs hosts and we specifically have a page here that lists out the users but also displays the number of posts that each user has so if we look at the code for this I've actually written a raw SQL query so I'm selecting all the fields that I need but I'm actually aggregating the total number of posts for each user and then grouping by ID and so this gives me the data that I need but it's actually of the unknown type because there's no way to actually infer the types of this raw query here and if you see my codes you can see that typescript is complaining it's like hey that's the unknown type

Chapter 3 1:03

syntax episode 839

Chapter 4 1:24

example overview

Chapter 5 1:36

the limitations of raw sql

and then inside this map users is the any type now of course the codes still work because it is giving me back in Array and these properties do exist here but this isn't the best workflow now you could Define your own type I could go in here and say yeah we're getting back an array of objects each one of those has these properties like this and now types script should be happy right if I go down here it's like all right well yeah I know that's an array with objects inside of it and yeah I know that these properties exist great but the types could lie right what if we go in and we change our query right what if I actually remove the email field from querying here typescript doesn't know about that we told typescript what the type would be exactly so it's say yeah of course there's an email field but if we go back to the page and refresh that email field isn't coming across anymore so this is one of the main issues of writing raw SQL code and potentially trying to keep that in sync with your types but now with Prisma type SQL we have a much better way to keep our types in sync with our queries so here in my Prisma folder if we look at our schema file you can see that I've enabled the type SQL feature here under preview features and then we can create a folder inside of our Prisma folder called SQL

Chapter 6 2:43

typedsql intro

and then Define our query queries inside of here so I have this query it's called get users with post count it's the exact same query as you saw in my codes but now we can actually generate types for this so from the command line if I do Prisma generate and pass in-- SQL it's going to see those SQL files and actually generate typed functions for us and now to use it I can import those typed functions from Prisma client SQL and you can see all of the SQL files I've defined are inside of there I specifically want the G users with postcount function and now instead of writing a raw query we can use our typed function so the way to do this is we say Prisma do query raw typed and then we can pass in the invocation of our typed function but now the types are flowing through we can see that this is an array typescript is Happy it knows what that user object is it knows what the properties are everything's awesome so if we head back over here and then refresh we get the data back and it works as expected but now if I update that query our types are going to stay in sync so if we head back over to that SQL file and let's say I did remove the email field we will need to regenerate

the types uh but they do support a --at opt so now anytime our SQL files change it's automatically going to regenerate those types so I removed the email field if we head back over to where we're querying it I would expect a type error whenever we're trying to access that email property now for my use cases I actually have to restart the typescript server because you can see that it's not actually picking up that latest type but in vs code if I restart the typescript server those latest types flow through and now we can see that we get a type error that says hey that email does not exist and so this is one of the great things about using type SQL here is now our types are going to stay in sync with our queries now they also support arguments so let's say I'm pulling in the post count from the query string and I only want to show users who have more posts than the specified post count we can update our query to say having greater than that specific post count and then I have a form here where the user can select their post count whenever they do that'll resubmit the form requery the data and load it accordingly so by default we have all the posts here but if I pass in plus five we only see the users that have more than five posts and if I do plus six we only see the users that have more

Chapter 7 4:28

typedsql with arguments

than six posts but how do we do this with type SQL we just use parameterized queries so here I have a SQL file get users by post count and now we have that having Clause here so we can filter it down and you can see I'm using dollar sign one and so whenever Prisma is generating these queries it's going to see that argument there it's also going to infer what the type is and now our typed function that we bring in is going to know that we need to pass in an argument and I have Prisma generate with the watch flag so the type should have been updated I'm just going to restart my typescript server and now I should be able to bring in get users by post count and then in our method here we can say Prisma do query raw typed and then pass in the call to that function but you'll notice we get a type error it's expecting us to pass in a number so we can actually pass in that post count there so now if I refresh the page it's using that typed query function but we're able to actually pass in arguments now there are some annotations you can add inside of your SQL files if the generated types aren't exactly what you're expecting so for instance you can specify the type of the arguments you

Chapter 8 5:47

customizing generated functions

can give them a name so that way you have good type completion and once you specify these commments those will be used when generating the types in terms of limitations they support my SQL postgress and sqlite because this is based on SQL you can't use this with mongodb and then the other thing is whenever we're generating the types we actually have to have an active database running to be able to do that and so locally I actually have a Docker container running so if I kill the docker container and then try to generate the types we're going to get an error because it actually needs that connection so it can do queries in order to actually infer the types and then the other thing is they don't support Dynamic SQL query so you can see in this example we are dynamically select The Columns based on like an actual string and our our code here you can't do that with uh type SQL queries now Prisma does mention that this was heavily inspired by PG typed and then also SQL X I haven't used either of these but it is cool to know there are other Solutions out there for actually generating typed SQL queries now this is still a preview feature so if you search the Prisma repo for issues that have type SQL in the name you can see that some various feature requests and bugs are popping up

Chapter 9 6:01

limitations of typedsql

Chapter 10 6:35

typedsql inspiration

Chapter 11 6:46

open issues

and specifically one that I ran into deals with having Json selects inside of your query so if you ever want to do any sort of Json aggregation or Json building or array building these types are not automatically inferred so I was testing this out in a database that has a bunch of information about restaurants and menu items and orders essentially I wanted to do some aggregation so I want to get all menu items within each menu item should have a nested object called restaurant that's all the restaurant info and then it should also have a nested item called category which is all the category info so this is a pretty complex uh SQL query here that I attempted to generate type SQL for and and if you look at the generated type you can see here for those nested Json objects it has a type of Json value and so when you're trying to access these nested properties here the types aren't automatically inferred so that's a limitation right now hopefully they'll Implement that in the future and so this will be really nice for when you're doing more complex Json aggregations like in in postgress queries so that's it for this video let me know down in the comments if you tried type SQL do you like it is this something that you're going to start using in your codebase as well and if you like this

Chapter 12 7:48

thanks!

video don't forget to like and if you want to see more don't forget to subscribe all right I'll see you in the next next one [Music]

Quote it with credit and a link. Quoting Syntax