Skip to content

fix: avoid coroutine leaks when the dialecter initialization fails.#6249

Merged
jinzhu merged 1 commit intogo-gorm:masterfrom
onlyice:fix/resource-leak
Apr 21, 2023
Merged

fix: avoid coroutine leaks when the dialecter initialization fails.#6249
jinzhu merged 1 commit intogo-gorm:masterfrom
onlyice:fix/resource-leak

Conversation

@onlyice
Copy link
Copy Markdown
Contributor

@onlyice onlyice commented Apr 19, 2023

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

When calling gorm.Open, there is the following code:

if config.Dialector != nil {
	err = config.Dialector.Initialize(db)
}

config.Dialector.Initialize(db) typically calls sql.OpenDB to create an *sql.DB, and starts an goroutine db.connectionOpener(ctx).

Next, a typical database driver will attempt to connect to the schema specified in the DSN. If an error occurs at this time (such as the specified schema not existing), it will cause config.Dialector.Initialize(db) to return an error. However, after receiving this error, GORM does not attempt to close *sql.DB. This causes the db.connectionOpener(ctx) goroutine to leak.

In my scenario, I used the wrong schema and retried calling gorm.Open multiple times. By observing the dumped goroutine, I found that there were a large number of db.connectionOpener(ctx) goroutines. After applying this code fix, these goroutines are no longer leaked.

This pull request try to close the *sql.DB variable if possible.

User Case Description

Same as above.

@onlyice
Copy link
Copy Markdown
Contributor Author

onlyice commented Apr 19, 2023

After observing the results of unit tests, it is believed that the failed tests are not related to this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants