# Core Architecture

# Core Architecture

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

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

- [docs/ai/dal-architecture.md](docs/ai/dal-architecture.md)
- [src/index.ts](src/index.ts)

</details>



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:

| Module | Purpose | Key Components |
|:---|:---|:---|
| **Meta** | Entity definitions and type mapping | `@Entity`, `getEntityPersistenceMeta`, `jsValueToPgParam` |
| **Query** | DSL and SQL generation | `Filter`, `Sort`, `buildSelectQuery`, `createStream` |
| **Repository** | CRUD and Data Access Logic | `Repository.find`, `Repository.addMany`, `Repository.update` |
| **DAL** | Connection and Pool Management | `Dal` gateway, `withClient`, `getDal` |

```mermaid
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 &lt;T&gt;"]
    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.

```mermaid
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](#2.1).

### 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](#2.2).

### 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](#2.3).

### 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](#4) and [Streaming Large Result Sets](#2.4).

### SQL Execution Pipeline
This diagram illustrates how a call to `repository.find()` moves through the system.

```mermaid
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]()

---
