Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing a globally defined db conn with multiple packages

Tags:

go

I've read a few StackOverflow answers on how we handling the db connection. Since it's a pool, we can define it globally and use it in multiple goroutines and it's safe.

The issue I'm having is that I have split my REST API into multiple packages. Each of these packages require a db connection, so I open a database connection in the startup. But even if I define the connection globally, it's only at the package level. What can I do to potentially share it among multiple packages?

For some context I'm using the PostgreSQL driver and gin-gonic in my application.

like image 308
user1952811 Avatar asked Jul 04 '15 07:07

user1952811


People also ask

How do I create a global database connection?

Approach 1: Use Global Variable Create a file db.go under a new subpackage sqldb . Declare a global variable DB of type *sql. DB to hold the database connection. Write a function that will open the connection and assign it to the global variable.

How many connections can a database have?

By default, SQL Server allows a maximum of 32767 concurrent connections which is the maximum number of users that can simultaneously log in to the SQL server instance.


1 Answers

There is also the option of creating another package to hold your database connection-related settings. It can then have a package level global, which can be initialized in main and used in any package that is importing it.

This way, you can explicitly see that the database package is being imported. Here is some sample code.

package database  var (     // DBCon is the connection handle     // for the database     DBCon *sql.DB ) 

package main  import "myApp/database"  func main() {      var err error     database.DBCon, err = sql.Open("postgres", "user=myname dbname=dbname sslmode=disable")  } 

package user  import "myApp/database"  func Index() {     // database handle is available here     database.DBCon      ... } 
like image 200
Maaz Avatar answered Sep 23 '22 12:09

Maaz