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

Core Architecture

Core Architecture

Relevant source files

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

  • docs/ai/dal-architecture.md
  • src/index.ts

The @primebrick/dal-pg library is structured into four distinct layers that transform high-level TypeScript entity definitions into optimized, parameterized PostgreSQL queries. This architecture prioritizes type safety, performance for bulk operations, and strict SQL injection prevention.

Module Structure

The codebase is organized into functional modules that handle specific stages of the data lifecycle:

ModulePurposeKey Components
MetaEntity definitions and type mapping@Entity, getEntityPersistenceMeta, jsValueToPgParam
QueryDSL and SQL generationFilter, Sort, buildSelectQuery, createStream
RepositoryCRUD and Data Access LogicRepository.find, Repository.addMany, Repository.update
DALConnection and Pool ManagementDal gateway, withClient, getDal
Code
graph TD subgraph "Application Layer" Entity["@Entity Class"] end subgraph "Metadata Layer (meta/)" Meta["EntityPersistenceMeta"] Coercion["Type Coercion (JS ↔ PG)"] end subgraph "Query Layer (query/)" DSL["Query DSL (Filter/Sort/Join)"] Builder["SQL Builder (buildSelectQuery)"] end subgraph "Engine Layer (repository/)" Repo["Repository <T>"] end subgraph "Infrastructure Layer (dal/)" DalGateway["Dal Gateway (Pool)"] PgDriver["node-pg / pg-query-stream"] end Entity -->|Decorators| Meta Meta --> Repo DSL --> Builder Builder --> Repo Repo --> DalGateway DalGateway --> PgDriver

Sources: docs/ai/dal-architecture.md:5-29, src/index.ts:17-145


Data Flow: From Entity to SQL

The transition from "Natural Language Space" (TypeScript classes) to "Code Entity Space" (SQL execution) follows a structured pipeline:

  1. Metadata Extraction: Decorators like @Entity and @Column register class properties in a WeakMap. The system uses Reflect.getMetadata("design:type") to infer PostgreSQL types (e.g., Date becomes timestamptz).
  2. Query Composition: Consumers use the Query DSL (field('name').eq('value')) to build abstract filter trees.
  3. SQL Building: The buildSelectQuery function consumes the metadata and DSL to produce a SqlQuery object containing a parameterized string and values.
  4. Execution: The Repository sends the query to the Dal gateway, which manages the pg.Pool and executes the command.

Mapping: TypeScript to PostgreSQL

The following diagram bridges the gap between TypeScript definitions and the underlying database schema managed by the DAL.

Code
classDiagram class "TypeScript Entity" { +UUID id @Key +String name @Column +Date createdAt @AuditableField } class "entity-ts-to-pg.ts" { <<Logic>> +inferPgType(designType) } class "PostgreSQL Table" { +uuid id PRIMARY KEY +text name +timestamptz created_at } "TypeScript Entity" ..> "entity-ts-to-pg.ts" : metadata discovery "entity-ts-to-pg.ts" ..> "PostgreSQL Table" : schema mapping

Sources: docs/ai/dal-architecture.md:31-66, src/meta/entity-meta.ts:17-45


Subsystem Interconnections

Entity Metadata System

The metadata system is the source of truth for all operations. It defines how property names map to snake_case columns and which fields are used for soft-deletion or auditing. For details, see Entity Metadata System.

Type Coercion

This layer ensures that JavaScript types (like Date or BigInt) are correctly formatted for the node-pg driver and that values returning from the wire are hydrated back into the expected JS format. For details, see Type Coercion: JS ↔ PostgreSQL.

Query DSL and SQL Builder

The DAL provides a functional DSL to avoid raw string manipulation. This system handles complex joins, projections, and filtering while enforcing strict identifier validation via assertValidIdentPart. For details, see Query DSL and SQL Builder.

Repository and Bulk Strategies

The Repository class implements different strategies based on the operation scale. While single writes use standard INSERT/UPDATE, bulk updates utilize a TEMP TABLE strategy to maintain atomicity and performance. For details, see Repository: CRUD and Finders and Streaming Large Result Sets.

SQL Execution Pipeline

This diagram illustrates how a call to repository.find() moves through the system.

Code
sequenceDiagram participant User as "Repository.find()" participant DSL as "query/dsl.ts" participant Builder as "query/query-builder.ts" participant Coercion as "meta/column-pg-io.ts" participant Driver as "pg.Pool" User->>DSL: Create Filter/Sort User->>Builder: buildSelectQuery(input) Builder->>Coercion: jsValueToPgParam(val) Builder-->>User: SqlQuery { text, values } User->>Driver: query(text, values) Driver-->>User: Row[] User->>Coercion: pgValueToJsValue(row)

Sources: docs/ai/dal-architecture.md:67-110, src/query/query-builder.ts:77-83


Last modified on July 13, 2026
Connection Pool and Session ConfigurationDal Gateway
On this page
  • Module Structure
  • Data Flow: From Entity to SQL
    • Mapping: TypeScript to PostgreSQL
  • Subsystem Interconnections
    • Entity Metadata System
    • Type Coercion
    • Query DSL and SQL Builder
    • Repository and Bulk Strategies
    • SQL Execution Pipeline