On Thursday, December 20, 2018 at 7:23:22 AM UTC-8, Nick wrote:
>
> Hi all, 
>
> I'm newish to Go, and I've been really enjoying using it. I'm still 
> getting to grips with the best practices of the language. 
>
> Up until now, I've used MarshalJSON methods on complex struct types 
> to easily save the state of data, using Marshal() from 
> encoding/json.  This has worked really well, and I have started to 
> get the simple power of interfaces with how easy it was to do. 
>
> I've got to the stage that it makes more sense to use SQL than JSON 
> for my data now, and I was thinking it would make most sense to have 
> a similar process to read and write SQL, using methods on my struct 
> data types, which can then be called by functions that take an 
> interface implementing those methods. 
>

What you're describing roughly fits into the category of an 
"object-relational mapping". Go has a number of solutions for that. One 
that pops to mind is GORM.
 

>
> I'm wondering if anybody else has done anything similar (I presume 
> so!), and could point me to examples of ways people have done this.   
> Any other thoughts on the best ways to organise my code to do this 
> cleanly and reusably would be very welcome indeed - as I say, I'm 
> new enough to Go that maybe I'm still thinking about this all wrong! 
>

There are two directions I've seen recommended in the Go community. Either 
use ORM, or sidestep it completely, and just implement the SQL directly.

I've found, for the places where I need to use SQL, that relationships are 
much more important than objects. So efficient interaction with the 
database ends up working best by simply directly writing SQL code, 
querying, and then scanning the results. ORMs would get in the way, because 
they would then require multiple ORM-level interactions to answer specific 
query. There's a little bit of repetitiveness in the non-ORM approach, but 
typically by the time I'm done, not so much that I'm concerned.

Unlike with Java, where introducing a new class of object requires a new 
source file, with the tailored query approach I can create a structure that 
is directly fit for purpose, and it is just a few lines of additional code 
in an existing file. This means my database layer can easily get exactly 
the columns I need, from exactly the tables I need, and map that into 
exactly the structure that I need.

A package like sqlx <https://github.com/jmoiron/sqlx> might even simplify 
your work even further.

Eric.
 

>
> Thanks in advance, 
>
> Nick 
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to