PrimebrickPrimebrick
  • Primebrick.dev
  • GitHub
  • Documentation
  • Services
  • Libraries
  • API Catalog
Resources
  • Landing Page
  • API Catalog
  • GitHub
PrimebrickPrimebrick

© 2026 Primebrick. MIT License.

github
DAL Library
    AI Agent Rules and SkillsAudit and Soft-Delete SubsystemsAudit Port and Delta TrackingAuditable Joins and Display NamesBulk OperationsCI/CD and Release ProcessConnection Pool and Session ConfigurationCore ArchitectureDal GatewayEntity Metadata SystemError HandlingGetting StartedGitFlow and Branching RulesGlossaryKey Design DecisionsOverviewQuery DSL and SQL BuilderRead OperationsRepository: CRUD and FindersStreaming Large Result SetsTest Infrastructure and EntitiesTest Suite CoverageTestingTimeout Management and withClientType Coercion: JS ↔ PostgreSQLWrite OperationsREADME
SDK Library
powered by Zudoku
DAL Library

Dal Gateway

Dal Gateway

Relevant source files

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

  • docs/ai/dal-usage-guide.md
  • src/dal/dal.ts

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

Code
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.


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

MechanismScopeDescription
statementTimeoutMsSessionGlobal default set on every connection in the pool.
withClient({ timeoutMs })ClientTemporary override for a single client session; reset on release.
BulkOptions.timeoutMsTransactionApplied via SET LOCAL for the duration of a bulk operation.

For details on manual transaction management and timeout overrides, see Timeout Management and withClient.

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


Child Pages

  • Connection Pool and Session Configuration: Deep dive into pg.Pool initialization, the DalConfig schema, and the onConnect lifecycle.
  • Timeout Management and withClient: Details on the withClient pattern for transactions and strategies for preventing timeout leakage.

Last modified on July 13, 2026
Core ArchitectureEntity Metadata System
On this page
  • Core Responsibilities
  • System Architecture
  • Key Components
    • Singleton Gateway (getDal)
    • Type Parser Registration
    • Session Configuration (onConnect)
  • Anti-Throttling and Safety Patterns
  • Child Pages