# Glossary

# Glossary

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

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

- [src/audit/auditable-types.ts](src/audit/auditable-types.ts)
- [src/dal/dal.ts](src/dal/dal.ts)
- [src/dal/type-parsers.ts](src/dal/type-parsers.ts)
- [src/errors/errors.ts](src/errors/errors.ts)
- [src/index.ts](src/index.ts)
- [src/meta/entity-decorators.ts](src/meta/entity-decorators.ts)
- [src/query/dsl.ts](src/query/dsl.ts)
- [src/repository/repository.ts](src/repository/repository.ts)
- [src/types/entities.ts](src/types/entities.ts)
- [src/types/types.ts](src/types/types.ts)

</details>



This page defines the core terminology, domain concepts, and technical jargon used within the `@primebrick/dal-pg` codebase. It serves as a reference for onboarding engineers to understand how natural language concepts map to specific code entities and implementation strategies.

## Core Concepts & Jargon

### Audit & Soft-Delete
The system implements a robust audit and soft-delete mechanism that tracks record lifecycles without physical deletion by default.

*   **Actor**: The identity (usually a UUID string) of the user or system performing a write operation. It is required for all `AuditableWriteOptions` [src/types/types.ts:53-56]().
*   **Audit Port**: An interface (`AuditPort`) that allows the DAL to emit audit events to an external consumer (e.g., an audit microservice) in a fire-and-forget manner [src/types/types.ts:86-88]().
*   **Delta**: A calculated object representing the difference between the `old` and `new` state of an entity during an update, used for audit logging [src/repository/repository.ts:53-64]().
*   **Soft-Delete**: The practice of marking a record as deleted by setting `deleted_at` and `deleted_by` fields rather than executing a SQL `DELETE` [src/types/entities.ts:7-10]().
*   **WithDeletedRecords**: A filter mode (`EXCLUDED`, `ONLY`, `INCLUDED`) that controls the visibility of soft-deleted rows in finder queries [src/types/types.ts:13-13]().

### Connection & Pool Management
The DAL manages a `pg.Pool` with specific "anti-throttling" configurations to ensure system stability.

*   **Dal Gateway**: The singleton entry point (`Dal` class) that owns the connection pool and manages the lifecycle of the database connection [src/dal/dal.ts:101-106]().
*   **OnConnect Hook**: A specialized handler that executes session-level SQL (like `SET search_path` and `SET statement_timeout`) every time a new client is created by the pool [src/dal/dal.ts:147-163]().
*   **Statement Timeout**: A safety mechanism (`statementTimeoutMs`) that kills long-running queries at the database level to prevent connection starvation [src/dal/dal.ts:66-69]().
*   **WithClient**: A pattern for executing a callback with a dedicated `PoolClient`, typically used for transactions or overriding timeouts [src/dal/dal.ts:223-238]().

### Metadata & Reflection
The DAL uses TypeScript decorators and reflection to map class definitions to database schemas.

*   **Entity Persistence Meta**: The internal representation of an entity's database structure, including table names and column mappings [src/meta/entity-meta.ts:44-55]().
*   **Implicit Columns**: Columns that are automatically discovered from class properties even if they lack a `@Column()` decorator [src/meta/entity-decorators.ts:134-155]().
*   **Snake_Case Convention**: The default behavior where class property names (camelCase) are mapped to SQL column names (snake_case) unless overridden [src/meta/entity-decorators.ts:11-13]().

---

## Natural Language to Code Mapping

The following diagrams bridge domain concepts to their specific implementations in the codebase.

### Data Access Flow
This diagram shows how a high-level request for data moves through the system entities.

```mermaid
graph TD
    subgraph "Consumer Space"
        User["App Code"]
    end

    subgraph "Gateway Layer"
        Dal["Dal Class [src/dal/dal.ts]"]
        Pool["pg.Pool [pg]"]
    end

    subgraph "Execution Layer"
        Repo["Repository [src/repository/repository.ts]"]
        DSL["Query DSL [src/query/dsl.ts]"]
        Builder["buildSelectQuery [src/query/query-builder.ts]"]
    end

    User -- "getDal()" --> Dal
    Dal -- "delegates to" --> Repo
    Repo -- "uses" --> DSL
    DSL -- "transformed by" --> Builder
    Builder -- "returns SqlQuery" --> Repo
    Repo -- "executes on" --> Pool
```
**Sources:** [src/dal/dal.ts:101-170](), [src/repository/repository.ts:148-150](), [src/query/query-builder.ts:78-83]()

### Entity Metadata Mapping
This diagram shows how decorators transform a TypeScript class into a database-aware entity.

```mermaid
graph LR
    subgraph "TypeScript Source"
        Class["@Entity class User"]
        PK["@Key() id"]
        Col["@Column() email"]
    end

    subgraph "Metadata Registry"
        WeakMap["META WeakMap [src/meta/entity-decorators.ts]"]
        Sync["syncImplicitEntityColumns"]
    end

    subgraph "Persistence Model"
        Meta["EntityPersistenceMeta [src/meta/entity-meta.ts]"]
        Hints["ColumnPgPersistenceHints [src/meta/column-pg-io.ts]"]
    end

    Class -- "registers" --> WeakMap
    PK -- "defines PK" --> Meta
    Col -- "defines SQL type" --> Hints
    WeakMap -- "processed by" --> Sync
    Sync -- "produces" --> Meta
```
**Sources:** [src/meta/entity-decorators.ts:106-125](), [src/meta/entity-meta.ts:157-168](), [src/meta/column-pg-io.ts:48-57]()

---

## Technical Glossary Table

| Term | Definition | Code Pointer |
| :--- | :--- | :--- |
| **AuditAction** | Enum defining write operations: `INSERT`, `UPDATE`, `SOFT_DELETE`, etc. | [src/types/types.ts:104-110]() |
| **AutoBatchSize** | Function calculating safe batch sizes to stay under PG's 65,535 parameter limit. | [src/repository/repository.ts:143-146]() |
| **ColumnPgPersistenceHints** | Metadata used to determine how JS types map to PG types (e.g., `timestamptz`). | [src/meta/column-pg-io.ts:56-56]() |
| **DalConfig** | Configuration object for pool size, timeouts, and application name. | [src/dal/dal.ts:54-84]() |
| **FieldRef** | A DSL object linking a specific entity class to a property key. | [src/query/dsl.ts:23-26]() |
| **IAuditableEntity** | Interface requiring `created_at/by`, `updated_at/by`, and `version`. | [src/types/entities.ts:13-19]() |
| **MatchBy** | The property used in the `WHERE` clause for updates/deletes (defaults to PK). | [src/types/types.ts:59-66]() |
| **Queryable** | A type union representing either a `Pool` or a `PoolClient`. | [src/repository/repository.ts:43-43]() |
| **TypeParsers** | Global overrides for `pg` to handle `bigint` (INT8) and `numeric` types. | [src/dal/type-parsers.ts:21-35]() |

---

## Implementation Details: Write Lifecycle

When a write operation (e.g., `add` or `update`) is performed via the `Repository`, the following flow is executed:

1.  **Metadata Resolution**: The repository fetches the `EntityPersistenceMeta` for the class [src/repository/repository.ts:159]().
2.  **Audit Check**: If the entity is auditable, it verifies that an `actor` is provided in the options [src/repository/repository.ts:32]().
3.  **Value Coercion**: JS values are converted to PG-compatible parameters using `jsValueToPgParam` [src/meta/column-pg-io.ts:52]().
4.  **SQL Execution**: The query is executed. All writes use `RETURNING *` to ensure the JS object is hydrated with database-generated defaults (like serial IDs or timestamps) [src/repository/repository.ts:169]().
5.  **Audit Emission**: If an `AuditPort` is present, a delta is calculated and `writeAudit` is called without awaiting the result (fire-and-forget) [src/types/types.ts:83-88]().

**Sources:** [src/repository/repository.ts:148-200](), [src/types/types.ts:44-56](), [src/meta/column-pg-io.ts:48-57]()
