Skip to content

Commit

Permalink
fix: sorry, too many connections.
Browse files Browse the repository at this point in the history
database/Sql.Rows.Close() should be called as it is
a safe to call and idempotent; not calling it will keep the
underlying connection open.

Added an integration test to reproduce the issue
and a fix to it.

Fixes minetest-go#53
  • Loading branch information
ronoaldo committed Feb 19, 2023
1 parent 7fe8a05 commit fc4a783
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions block/block_postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func (repo *postgresBlockRepository) GetByPos(x, y, z int) (*Block, error) {
if err != nil {
return nil, err
}
defer rows.Close()
if !rows.Next() {
return nil, nil
}
Expand Down
39 changes: 39 additions & 0 deletions block/block_postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,42 @@ func TestPostgresBlocksRepo(t *testing.T) {
blocks_repo := block.NewBlockRepository(db, types.DATABASE_POSTGRES)
testBlocksRepository(t, blocks_repo)
}

func TestMaxConnections(t *testing.T) {
db, err := getPostgresDB(t)
assert.NoError(t, err)

assert.NoError(t, block.MigrateBlockDB(db, types.DATABASE_POSTGRES))
blocks_repo := block.NewBlockRepository(db, types.DATABASE_POSTGRES)
assert.NotNil(t, blocks_repo)

var maxConnections int
row := db.QueryRow("show max_connections;")
err = row.Scan(&maxConnections)
assert.NoError(t, err)
t.Logf("Testing against %v max connections", maxConnections)

fakeBlock := block.Block{
PosX: 1,
PosY: 1,
PosZ: 1,
Data: []byte("test"),
}
if err := blocks_repo.Update(&fakeBlock); err != nil {
t.Fatalf("Error setting up test case: %v", err)
}

// Run more than max_connections query operations in a loop
count := 0
for i := 0; i < maxConnections*2; i++ {
b, err := blocks_repo.GetByPos(1, 1, 1)
count++
if b != nil && count%10 == 0 {
t.Logf("Executed %d operations. b=%v", count, b)
}
if err != nil {
t.Errorf("Unexpected error after %d operations: %v", count, err)
break
}
}
}
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ services:
- PGPORT=5432
- LOGLEVEL=debug
working_dir: /data
command: ["go", "test", "./...", "-cover"]
command: ["go", "test", "./...", "-v", "-cover"]

volumes:
postgres: {}

0 comments on commit fc4a783

Please sign in to comment.