Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 7, 2022 01:02 am GMT

Stop writing your SQL code inside your Go source files!

You are writing Go but you need to write some SQL, so you end up writing SQL inside your Go source code, this is not a problem as long as they are short queries, but when your queries take up more lines of code they become hard to read and to modify, besides the lack of indentation and coloring of the code make it worse.

So... What is the solution?

Keep your SQL code as SQL and your Go code as Go (don't write SQL inside Go).

For this you can use sqload!

File users.sql

-- query: FindUserByIdSELECT first_name,       last_name,       dob,       email  FROM user WHERE id = :id;-- query: UpdateFirstNameByIdUPDATE user   SET first_name = :first_name WHERE id = :id;-- query: DeleteUserByIdDELETE FROM user WHERE id = :id;

File main.go

package mainimport (    _ "embed"    "fmt"    "github.com/midir99/sqload")//go:embed users.sqlvar sqlCode stringvar Q = sqload.MustLoadFromString[struct {    FindUserById        string `query:"FindUserById"`    UpdateFirstNameById string `query:"UpdateFirstNameById"`    DeleteUserById      string `query:"DeleteUserById"`}](sqlCode)func main() {    fmt.Printf("- FindUserById
%s

", Q.FindUserById) fmt.Printf("- UpdateFirstNameById
%s

", Q.UpdateFirstNameById) fmt.Printf("- DeleteUserById
%s

", Q.DeleteUserById)}

By keeping your SQL and Go separate you get the following advantages:

  • Better support by your IDE or code editor (because you are now handling SQL code in its own file with its .sql extension).
  • Your DBA will be able to easily find the code of each query that your project is running.
  • SQL reuse, simply copy the same .sql files from one project to another.
  • Keep your Go code free of SQL queries.

sqload is a library with 100% test coverage, free of dependencies
from third parties and their documentation has many examples.

sqload is inspired by Yesql (Clojure).

https://github.com/midir99/sqload
https://pkg.go.dev/github.com/midir99/sqload


Original Link: https://dev.to/midir99/stop-writing-your-sql-code-inside-your-go-source-files-1768

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To