> ## Documentation Index
> Fetch the complete documentation index at: https://sonamu.cartanova.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Database Connection

> Troubleshooting DB connection issues

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

## DB Connection Resource Leak

### Symptoms

```bash theme={null}
Error: remaining connection slots are reserved for non-replication superuser connections
```

Or

```bash theme={null}
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:**

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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:

```sql theme={null}
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

```bash theme={null}
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

```bash theme={null}
# 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:

```bash theme={null}
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=your_database
```

#### 3. Manual Connection Test

```bash theme={null}
psql -h localhost -p 5432 -U postgres -d your_database
```

If successful, psql prompt appears after password input.

## Timeout Error

### Symptoms

```bash theme={null}
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`:

```typescript theme={null}
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

```sql theme={null}
-- 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

```sql theme={null}
-- 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

```bash theme={null}
Error: permission denied for table users
```

### Solution

```sql theme={null}
-- 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

```bash theme={null}
Error: database "miomock_test" already exists
```

Or

```bash theme={null}
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

```bash theme={null}
# 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`:

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

#### 3. Check Test Setup/Teardown

```typescript theme={null}
// vitest.config.ts
export default defineConfig({
  test: {
    globalSetup: "./test/setup.ts",
    globalTeardown: "./test/teardown.ts",
  },
});
```

```typescript theme={null}
// test/teardown.ts
export default async function teardown() {
  await DB.clearTestTransaction();
  await DB.closeConnection();
}
```

## Related Documentation

* [Migration Errors](/en/troubleshooting/common-errors/migration-errors)
* [Using Fixtures](/en/testing/fixtures/test-database)
* [Database Configuration](/en/configuration/sonamu-config/database)
