DEV Community

Type-safe Data Access in Go using Prisma and sqlc

Gabriel Lemire on December 05, 2023

I recently started a new project in Go where I needed a database. It was an opportunity to select a stack I was happy with. In the past, I had used...
Collapse
 
rametta profile image
Jason

Great article Gabriel! First time learning about sqlc and it looks pretty neat.

I think if I was starting a new Go project from scratch, I like the idea of using Prisma for the schema authoring and generation of migration files, but instead of writing the raw queries in sql files and have sqlc generate the Go code from those, I would probably just try to use something like the prisma Go client , which I know is ORM-y but it also provides the ability to write raw queries like:

var posts []db.RawPostModel
err := client.Prisma.QueryRaw("SELECT * FROM `Post` WHERE id = ? AND title = ?", "123abc", "my post").Exec(ctx, &posts)
Enter fullscreen mode Exit fullscreen mode

Which is nice for those complex queries that are sometimes needed. It also reduces the amount of generation steps I feel, making it a bit less brittle, but also the downside is more work for the dev.

It's all trade-offs at the end of the day. My next Go project, I will look into both methods and test them out to see what I like more!

Collapse
 
gretro profile image
Gabriel Lemire

Hey Jason. Thanks for your comment. I found the best thing about sqlc is the compile-time safety of types. It will not let you create a query against tables and columns it does not know.

This avoids you having to find out about your broken queries at runtime.

Collapse
 
amb profile image
Andrew

Hi, great post! I am one of the maintainers of sqlc and just wanted to mention that you can actually specify a directory of migrations as your schema to sqlc. You don't have to put everything in one file.

Also we just announced the first alpha release of our TypeScript plugin, which does what you'd expect (generates TypeScript from your SQL). It would be great to have anyone who's interested try it out!

Collapse
 
gretro profile image
Gabriel Lemire

Hi Andrew. I've added a few edits to the article to reflect the information in your comment. Thank you for correcting me :)

You are contributing to a great project. Keep up the good work.

Collapse
 
wiliamvj profile image
Wiliam V. Joaquim

wow, great solution