aws / aws-lambda-go

Libraries, samples and tools to help Go developers develop AWS Lambda functions.
Apache License 2.0
3.62k stars 548 forks source link

Database connection #94

Closed fi0 closed 6 years ago

fi0 commented 6 years ago

What's the recommended way to open and close a database connection?

os2tux commented 6 years ago

The Go documentation for the SQL library has very good information on how to handle database connections. I've included a couple of links to some documentation you might find useful. I've been using that package extensively for projects and would be glad to help with any questions about its usage. Thanks!

https://github.com/golang/go/wiki/SQLInterface

http://go-database-sql.org/

Kansuler commented 6 years ago

You can have persistent database connection by storing the connection in a global variable as long as the lambda container runs. It will then establish a new connection if it starts from a cold state. This way you'd not have to open and close a connection on each request to the lambda, which is quite expensive and slow.

I don't think there is any way to close the connection when the lambda container stops.

import "database/sql"

var db *sql.DB

func NewConnection(connection string) (*sql.DB, error) {
    // Check if a connection is already open
    if db != nil {
        return db, nil
    }

    return sql.Open("postgres", connection)
}
julienbonastre commented 8 months ago

You can have persistent database connection by storing the connection in a global variable as long as the lambda container runs. It will then establish a new connection if it starts from a cold state. This way you'd not have to open and close a connection on each request to the lambda, which is quite expensive and slow.

I don't think there is any way to close the connection when the lambda container stops.

import "database/sql"

var db *sql.DB

func NewConnection(connection string) (*sql.DB, error) {
  // Check if a connection is already open
  if db != nil {
      return db, nil
  }

  return sql.Open("postgres", connection)
}

What am I missing here? that global var is never initialised in this snippet so it would always return nil and thus instantiate a new connection??

wcheek commented 1 month ago

@julienbonastre I think you're right that something is amiss. You need to create the new connection if it is nil - this is stored in the global var db and is available on future executions.

Mine is working like this:

var db *sql.DB

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    if db == nil {
        db = GetDatabaseConnection()
    }
  ...
}

func main() {
    lambda.Start(HandleRequest)
}