---
title: "Database Migration Query Merger"
description: "The Migrate -> MergeQueries execution flow represents the end-to-end lifecycle of schema migration execution within Drizzle ORM's PostgreSQL and Netlify Database adapters. When a user triggers data..."
last_updated: "2026-10-12T08:14:00.757955+00:00"
canonical_url: "https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/how-it-works/database-migration-query-merger"
---


## Overview

### Introduction

The **Migrate -> MergeQueries** execution flow represents the end-to-end lifecycle of schema migration execution within Drizzle ORM's PostgreSQL and Netlify Database adapters. When a user triggers database migrations, migration files are parsed, converted into executable `SQL` templates, compiled into database-ready query strings with parameterized values, and finally merged into cohesive query batches executed via a database session transaction.


---

## Step-by-Step Execution Trace

### Step 1: Netlify-DB Migration Entrypoint

The migration process can initiate from the Netlify Database adapter's `migrate` function. It checks whether the provided database instance is an instance of `NodePgDatabase`. If so, it delegates execution directly to the Node-Postgres migrator; otherwise, it reads migration files from disk/configuration and passes them to the underlying database session dialect.


### Step 2: Node-Postgres Migration Entrypoint

For standard Node-Postgres setups, the `migrate` function loads the migration metadata using `readMigrationFiles(config)` and invokes `db.dialect.migrate(...)` with the parsed migrations, database session, and configuration.


### Step 3: PostgreSQL Dialect Migration Handler

The `PgDialect.migrate` method sets up the migrations tracking table (`__drizzle_migrations`), checks existing records in the database, opens a transaction, and loops through unapplied migration scripts, executing individual statements inside a transaction block.


### Step 4: Session Execution & Query Preparation

When `tx.execute(...)` is called with an `SQL` template object, the `PgSession` wraps the operation inside active telemetry spans, turning the raw `SQL` object into a prepared query via `this.dialect.sqlToQuery(query)`.


### Step 5: Dialect SQL-to-Query Conversion

`PgDialect.sqlToQuery` acts as a bridge, invoking `sql.toQuery(...)` with dialect-specific configurations such as custom casing rules, parameter escaping, and typing functions.


### Step 6: SQL Object Query Compilation

`SQL.toQuery` initiates an active OpenTelemetry tracing span (`drizzle.buildSQL`) and invokes `buildQueryFromSourceParams` over the internal query chunks to compile textual SQL and parameter lists.


### Step 7: Building Query from Source Parameters

`buildQueryFromSourceParams` iterates through every `SQLChunk` inside the expression tree—handling strings, names, identifiers, tables, parameters, and nested `SQL` objects—producing a list of partial `QueryWithTypings` objects.


### Step 8: Merging Queries

`mergeQueries` aggregates an array of `QueryWithTypings` chunks into a single, unified `QueryWithTypings` result object by concatenating SQL strings, accumulating parameter arrays, and merging type definitions.


---

## Architecture Diagrams

### Sequence Diagram

```mermaid
sequenceDiagram
    autonumber
    participant NetlifyMigrator as netlify-db/migrator.ts
    participant NodePgMigrator as node-postgres/migrator.ts
    participant PgDialect as pg-core/dialect.ts
    participant PgSession as pg-core/session.ts
    participant SQLObj as sql/sql.ts (SQL)

    alt Netlify DB (Non-NodePg)
        NetlifyMigrator->>PgDialect: migrate(migrations, session, config)
    else Node-Postgres / NodePg fallback
        NetlifyMigrator->>NodePgMigrator: migrate(db, config)
        NodePgMigrator->>PgDialect: migrate(migrations, session, config)
    end

    loop For each unapplied migration statement
        PgDialect->>PgSession: tx.execute(sql)
        PgSession->>PgDialect: sqlToQuery(query)
        PgDialect->>SQLObj: sql.toQuery(config)
        SQLObj->>SQLObj: buildQueryFromSourceParams(chunks, config)
        SQLObj->>SQLObj: mergeQueries(queries)
        SQLObj-->>PgDialect: QueryWithTypings
        PgDialect-->>PgSession: Executed query result
    end
```


### Flowchart

```mermaid
flowchart TD
    A[Migrate Entrypoint] --> B{Is NodePgDatabase?}
    B -- Yes --> C[NodePg Migrate]
    B -- No --> D[Read Migration Files]
    C --> D
    D --> E[PgDialect.migrate]
    E --> F[Execute Migration Statements]
    F --> G[PgSession.execute]
    G --> H[PgDialect.sqlToQuery]
    H --> I[SQL.toQuery]
    I --> J[buildQueryFromSourceParams]
    J --> K[mergeQueries]
    K --> L[Database Transaction Execution]
```


---

## Key Observations

- **Cross-Module Boundaries:** The execution flow seamlessly traverses driver-specific migrators (`netlify-db`, `node-postgres`), core database dialects (`pg-core`), active session managers, and core SQL query construction primitives (`sql/sql.ts`).
- **Transaction Safety:** Migration scripts are executed sequentially inside a database transaction (`session.transaction`), ensuring that schema updates are atomic and rolling back if any statement fails.
- **Telemetry & Tracing:** OpenTelemetry spans (`drizzle.operation`, `drizzle.prepareQuery`, `drizzle.buildSQL`) wrap query preparation and execution phases to monitor performance overhead.


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/e1b68fed-3c4e-4c95-b2ba-ebf050f78025/llms.txt) for all pages in this wiki.
