realworld-starter-kit icon indicating copy to clipboard operation
realworld-starter-kit copied to clipboard

SQL Connection & Go ORM

Open JackyChiu opened this issue 7 years ago • 11 comments

I'm quite new to using SQL with Go, so if anyone has any opinion or design proposals post them here!

As of now:

  • The SQL Connection is global in the main package (Maybe switch to dependency injection to pass it around?)
  • We're using gorm as our ORM, maybe we don't need an ORM and sqlx would be enough?

JackyChiu avatar Apr 28 '17 21:04 JackyChiu

  • DI would be preferable since it would make the code much more testable..... Plus it can also work as the application context pool

This could change to

func RegisterUser(db *SqlxBlah) error {
    return func (w http.ResponseWriter, h *http.Request) {
     //old code
   }
}
  • Sqlx would be more than enough though .

adelowo avatar Apr 29 '17 00:04 adelowo

@adelowo yeah I definitely agree that DI was the way to go, I'll look into this approach!

For the example you posted, would you need to change it to this?

func RegisterUser(db *SqlxBlah, w http.ResponseWriter, h *http.Request) error {
    return func (w http.ResponseWriter, h *http.Request) {
     //old code
   }
}

How do you feel about the ORM? I started off with that just to get something up

JackyChiu avatar Apr 29 '17 00:04 JackyChiu

  • While what you are proposing works, i just like to stay too close to holy http.Handler interface..

  • I tried the ORM some time ago, didn't feel natural.. Plain sql for me is the way to go.

adelowo avatar Apr 29 '17 00:04 adelowo

I should be able to help out on a couple things though

adelowo avatar Apr 29 '17 00:04 adelowo

@adelowo sorry I just wasn't too sure what you were saying but I think I see it now for the http.handler!

Yeah if you could show an example without the ORM I'd really appreciate it! And feel free to contribute to any part 😄

JackyChiu avatar Apr 29 '17 00:04 JackyChiu

Can i pull a fork of this showing that ? or how do you want me to "show the example" ?

adelowo avatar Apr 29 '17 01:04 adelowo

Can i pull a fork of this showing that ? or how do you want me to "show the example" ?

Yeah a fork, a gist, or whatever works 😁

JackyChiu avatar Apr 29 '17 01:04 JackyChiu

A fork it shall be... Should get that done in a couple hours

adelowo avatar Apr 29 '17 01:04 adelowo

Ok, i found out i already have something like this..

You might want to look into it

Database => https://github.com/adelowo/reblog/tree/master/models (plus mocks) Handlers => https://github.com/adelowo/reblog/tree/master/handler

https://github.com/adelowo/reblog/blob/master/main.go#L24

adelowo avatar Apr 29 '17 07:04 adelowo

I agree with the DI approach. This article does a good job showing a few approach. http://www.alexedwards.net/blog/organising-database-access

qwo avatar May 01 '17 14:05 qwo

Yep I've switch it using DI!

JackyChiu avatar May 01 '17 14:05 JackyChiu