Turned NewDBConnection into a singleton, added database tests.#40
Turned NewDBConnection into a singleton, added database tests.#40andrew-sledge wants to merge 1 commit intomcpjungle:mainfrom
NewDBConnection into a singleton, added database tests.#40Conversation
| db, err = gorm.Open(dialector, c) | ||
|
|
||
| if err != nil { | ||
| dbErr = fmt.Errorf("failed to connect to database: %w", err) |
There was a problem hiding this comment.
Do we really need both err and dbErr variables?
Since we will anyway return db, err, why don't we get rid of dbErr var?
In case of error, we directly assign our error to err, like:
err = fmt.Errorf(...)
Then, just returning db, err is good enough.
Am I missing something here?
There was a problem hiding this comment.
The thought was a little in preparation for structured logging. For instance if you want to wrap the error with an error code, datetime, etc. the error returned from gorm may not completely wrap it in the way that you want. I'm not too passionate about it so if you want it changed I can do that - just trying to save a couple of steps down the road.
| } | ||
| } | ||
|
|
||
| func TestNewDBConnection_PostgresDSN(t *testing.T) { |
There was a problem hiding this comment.
This test currently fails always.
This is because the NewDBConnection() already ran once for the first test so it returns a db and no error, which fails this test.
If you re-order the tests, then the other one will fail. Only the first test passes because the second time, sync.Once() doesn't run the logic again (which is expected behavior).
Is there a way to "reset" the NewDBConnection() function? We must reset it for every testcase.
There was a problem hiding this comment.
Good catch - I was running these individually in my IDE. Working on this...
|
One thing to think about - instead of using a singleton it might be preferable to use dependency injection. DI would make testing easier and give you more flexibility for data connection types because it would implement an interface. |
|
@andrew-sledge I'm open to dependency injection too. The singleton idea came up because the DB object is currently its own package. |
|
@duaraghav8 yep - that's probably the best way. |
67f2579 to
6709e3a
Compare
e6f9f3d to
321f552
Compare
No description provided.