# Dal Gateway

# Dal Gateway

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [docs/ai/dal-usage-guide.md](docs/ai/dal-usage-guide.md)
- [src/dal/dal.ts](src/dal/dal.ts)

</details>



The `Dal` class serves as the high-level entry point for the `@primebrick/dal-pg` library. It centralizes pool management, type parsing, and session configuration into a single process-wide gateway. While the `Repository` class handles the low-level SQL generation and execution, the `Dal` class provides the infrastructure and lifecycle management required for robust database interactions in a high-concurrency environment.

### Core Responsibilities

The `Dal` gateway is designed to solve three primary concerns:
1.  **Pool Ownership & Lifecycle**: Managing a `pg.Pool` with best-practice defaults to prevent connection exhaustion and "stuck" queries.
2.  **Singleton Pattern**: Ensuring a single instance per database connection string to avoid redundant resource allocation.
3.  **Type Parser Registration**: Automatically configuring global PostgreSQL-to-JS type mappings (e.g., `INT8` to `bigint`) upon initialization.

### System Architecture

The following diagram illustrates how the `Dal` class bridges the application code with the underlying PostgreSQL driver and the internal `Repository` engine.

**Dal Gateway Context Diagram**
```mermaid
graph TD
    subgraph "Application Space"
        [AppCode] --> |"getDal(config)"| DAL["Dal (Singleton)"]
    end

    subgraph "Code Entity Space (Internal)"
        DAL --> |"owns"| POOL["pg.Pool"]
        DAL --> |"delegates to"| REPO["Repository"]
        DAL --> |"initializes"| TP["type-parsers.ts"]
    end

    subgraph "Database Space"
        POOL --> |"manages"| CONN["PostgreSQL Connections"]
        CONN --> |"SET application_name"| PG_STAT["pg_stat_activity"]
    end

    [AppCode] -.-> |"Optional Transaction"| WC["dal.withClient()"]
    WC --> |"provides"| REPO_CLIENT["Repository (PoolClient)"]
```
Sources: [src/dal/dal.ts:1-31](), [src/dal/dal.ts:101-170]()

---

### Key Components

#### Singleton Gateway (`getDal`)
The library enforces a singleton pattern via the `getDal()` factory. This ensures that the same `pg.Pool` is reused across all requests, preventing memory leaks and connection spikes. If a consumer attempts to call `getDal()` with a different connection string than the one already initialized, the library throws an error to prevent accidental multi-DB cross-talk within a single instance.

#### Type Parser Registration
Upon construction, the `Dal` class calls `ensureTypeParsers()`. This is an idempotent operation that registers global parsers for PostgreSQL types that do not map naturally to JavaScript, such as converting `INT8` (bigint) and `NUMERIC` to appropriate JS types.
Sources: [src/dal/dal.ts:127-128](), [src/dal/dal.ts:25-36]()

#### Session Configuration (onConnect)
Every time the pool creates a new connection, the `Dal` gateway executes an `onConnect` hook. This hook standardizes the session environment by setting:
*   `search_path`: Ensures queries target the correct schema.
*   `statement_timeout`: Prevents runaway queries from starving the pool.
*   `application_name`: Improves observability in `pg_stat_activity`.

For details on how these settings are applied and managed, see **[Connection Pool and Session Configuration](#3.1)**.

---

### Anti-Throttling and Safety Patterns

The `Dal` gateway is built with a "fail-fast" and "anti-throttling" philosophy. By default, it applies a `statement_timeout` (default 30s) to every connection. This ensures that if a query hangs or a network partition occurs, the connection is eventually released back to the pool rather than being held indefinitely.

**Timeout Interaction Map**
| Mechanism | Scope | Description |
| :--- | :--- | :--- |
| `statementTimeoutMs` | Session | Global default set on every connection in the pool. |
| `withClient({ timeoutMs })` | Client | Temporary override for a single client session; reset on release. |
| `BulkOptions.timeoutMs` | Transaction | Applied via `SET LOCAL` for the duration of a bulk operation. |

For details on manual transaction management and timeout overrides, see **[Timeout Management and withClient](#3.2)**.

Sources: [src/dal/dal.ts:15-31](), [docs/ai/dal-usage-guide.md:124-133]()

---

### Child Pages

*   **[Connection Pool and Session Configuration](#3.1)**: Deep dive into `pg.Pool` initialization, the `DalConfig` schema, and the `onConnect` lifecycle.
*   **[Timeout Management and withClient](#3.2)**: Details on the `withClient` pattern for transactions and strategies for preventing timeout leakage.

---
