Skip to main content
This covers common database connection-related problems in Sonamu and how to resolve them.

DB Connection Resource Leak

Symptoms

Error: remaining connection slots are reserved for non-replication superuser connections
Or
Error: too many connections for database
This occurs when running development server for a long time or repeating Fixture operations.

Cause

When DB connections are created and an error occurs, destroy() is not called, causing connections to accumulate without being cleaned up. Problematic code pattern:
const db = createKnexInstance(config);

// Perform multiple operations
await db.raw("SELECT ...");
await db.raw("UPDATE ...");  // Error occurs here

await db.destroy();  // Never reached

Solutions

1. Use try-finally Pattern

const db = createKnexInstance(config);

try {
  await db.raw("SELECT ...");
  await db.raw("UPDATE ...");
  return result;
} finally {
  await db.destroy();  // Executes regardless of error
}

2. Clean Up Multiple DB Connections

const sourceDB = createKnexInstance(sourceConfig);
const targetDB = createKnexInstance(targetConfig);

try {
  // Perform operations
  const data = await sourceDB.select("*").from("users");
  await targetDB.insert(data).into("users");
  return data;
} finally {
  await targetDB.destroy();
  await sourceDB.destroy();
}

3. Check Current Connection Count

To check current connection status in PostgreSQL:
SELECT
  datname,
  count(*) as connections,
  max_conn
FROM pg_stat_activity
JOIN pg_database ON pg_stat_activity.datname = pg_database.datname
WHERE pg_database.datname = 'your_database_name'
GROUP BY datname, max_conn;

Prevention

  • Always use try-finally when creating DB connections directly
  • Using BaseModel methods automatically manages connections
  • Use FixtureManager methods for Fixture operations (includes automatic cleanup)

Connection Configuration Error

Symptoms

Error: connect ECONNREFUSED 127.0.0.1:5432

Causes

  1. PostgreSQL server is not running
  2. DB configuration in .env file is incorrect
  3. Port number is wrong

Solutions

1. Check PostgreSQL Running

# macOS (Homebrew)
brew services list
brew services start postgresql

# Linux (systemd)
sudo systemctl status postgresql
sudo systemctl start postgresql

2. Check Connection Information

Check .env file:
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=your_database

3. Manual Connection Test

psql -h localhost -p 5432 -U postgres -d your_database
If successful, psql prompt appears after password input.

Timeout Error

Symptoms

Error: Timeout acquiring a connection. The pool is probably full.

Causes

  1. DB connection pool exhausted
  2. Long-running queries holding connections
  3. Connection pool settings too small

Solutions

1. Adjust Connection Pool Settings

sonamu.config.ts:
export default {
  database: {
    miomock: {
      host: "localhost",
      port: 5432,
      user: "postgres",
      password: "password",
      database: "miomock",
      pool: {
        min: 2,
        max: 10,  // Increase from default
        acquireTimeoutMillis: 30000,  // Increase timeout
        idleTimeoutMillis: 30000
      }
    }
  }
} satisfies SonamuConfig;

2. Check Long-Running Queries

-- Check currently running queries
SELECT
  pid,
  now() - query_start as duration,
  query
FROM pg_stat_activity
WHERE state = 'active'
ORDER BY duration DESC;

-- Kill specific query
SELECT pg_cancel_backend(pid);  -- Graceful termination
SELECT pg_terminate_backend(pid);  -- Force termination

3. Check Uncommitted Transactions

-- Check old transactions
SELECT
  pid,
  now() - xact_start as duration,
  state,
  query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY duration DESC;

Permission Error

Symptoms

Error: permission denied for table users

Solution

-- Check database owner
SELECT d.datname, u.usename
FROM pg_database d
JOIN pg_user u ON d.datdba = u.usesysid
WHERE d.datname = 'your_database';

-- Grant schema permissions
GRANT ALL ON SCHEMA public TO your_user;

-- Grant table permissions
GRANT ALL ON ALL TABLES IN SCHEMA public TO your_user;

-- Grant sequence permissions
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO your_user;

Test Environment DB Conflict

Symptoms

Error: database "miomock_test" already exists
Or
Error: database "miomock_test" is being accessed by other users

Causes

  • Previous test didn’t terminate properly, leaving test DB
  • Multiple test processes running simultaneously

Solutions

1. Force Delete Test DB

# Terminate all connections and delete DB
psql -U postgres -c "
  SELECT pg_terminate_backend(pid)
  FROM pg_stat_activity
  WHERE datname = 'miomock_test' AND pid <> pg_backend_pid();
"

psql -U postgres -c "DROP DATABASE IF EXISTS miomock_test;"

2. Isolate Test Execution

package.json:
{
  "scripts": {
    "test": "vitest run --pool=forks --poolOptions.forks.singleFork=true"
  }
}

3. Check Test Setup/Teardown

// vitest.config.ts
export default defineConfig({
  test: {
    globalSetup: "./test/setup.ts",
    globalTeardown: "./test/teardown.ts"
  }
});
// test/teardown.ts
export default async function teardown() {
  await DB.clearTestTransaction();
  await DB.closeConnection();
}