Getting Started
Database Drivers
Schema Integrations
Seed Generators
Utilities and Testing
The following files were used as context for generating this wiki page:
Schema Introspection is the process of querying a live database to reconstruct its structure (tables, columns, constraints, indexes, and relations) into an internal representation. This subsystem acts as the bridge between raw database metadata and the ORM's type-safe schema definitions. By systematically querying the system catalogs (e.g., pg_catalog, information_schema), the introspector captures the state of the database, enabling features like schema comparison, migration generation, and the "push" workflow.
The core design centers around two primary phases: data extraction and serialization. The extraction phase executes low-level SQL to pull metadata, while the serialization phase converts this raw result set into a normalized, type-agnostic JSON-like object. This architecture decouples the database-specific SQL dialect from the business logic required to generate code or compare schemas.
The subsystem manages complexity by handling heterogeneous database constructs, including materialized views, foreign keys, identity columns, and custom policy definitions. It addresses the common pain point of drift between code-first schema definitions and the actual database reality, ensuring that developers can maintain accurate, up-to-date type definitions even when the underlying schema evolves independently.
The extraction process is initiated through fromDatabase functions, which iterate through tables, views, and materialized views based on provided filters. The logic heavily relies on joining pg_catalog tables to resolve object dependencies such as schema names, serial sequences, and enum definitions.
Sources: drizzle-kit/src/serializer/pgSerializer.ts:968-1916
The mechanism uses a progressCallback to monitor the long-running execution of fetching columns, indexes, and foreign keys. A critical guard exists inside fromDatabase where tablesFilter is applied to avoid redundant processing, preventing unrequested schemas from polluting the snapshot.
Serialization transforms raw database types into consistent internal representations used by the Drizzle Kit. For Postgres, generatePgSnapshot performs the conversion from internal Drizzle-ORM core table configurations into structured schema snapshots.
Important
The serialization layer uses getColumnCasing to map column names based on user configuration, ensuring that even if the database uses snake_case, the generated Drizzle code can be configured for camelCase.
The buildArrayString helper is a core utility here, converting JavaScript arrays into the PostgreSQL '{...}' format, handling edge cases for dates and JSON values to ensure type parity.
Sources: drizzle-kit/src/serializer/pgSerializer.ts:101-112, drizzle-kit/src/serializer/pgSerializer.ts:72-99
The schemaToTypeScript function transforms the serialized schema snapshot into a valid string of TypeScript code. It computes the necessary imports by scanning table columns, foreign keys, and indexes.
serial, varchar, etc.) and constraints (unique, check).pgTable definition block, appending chainable methods like .primaryKey() or .notNull() based on the properties found in the snapshot.Sources: drizzle-kit/src/introspect-pg.ts:309-636
Identity columns require special treatment to capture sequence parameters. The generateIdentityParams function creates the appropriate chainable call for either .generatedAlwaysAsIdentity() or .generatedByDefaultAsIdentity().
Sources: drizzle-kit/src/introspect-pg.ts:277-302, drizzle-kit/src/serializer/pgSerializer.ts:173-180
In schemas with circular foreign keys, Drizzle Kit must inject types to avoid circular reference errors during compilation. isCyclic and isSelf perform the check by comparing tableFrom and tableTo. If a cyclic reference is detected, the introspector identifies necessary import adjustments.
Warning
Cyclic dependencies, if not detected correctly, can break the generated TypeScript file due to temporal dead zones or circular module imports. The introspector relies on the relations set to detect if a relationship is already registered in the other direction.
Sources: drizzle-kit/src/introspect-pg.ts:638-646, drizzle-kit/src/introspect-pg.ts:333-335
This example demonstrates the workflow for manual schema inspection using the provided utilities.
// Usage: Inspecting a Postgres database
import { fromDatabase } from 'drizzle-kit/src/serializer/pgSerializer';
import { schemaToTypeScript } from 'drizzle-kit/src/introspect-pg';
// 1. Fetch current schema from DB
const schema = await fromDatabase(dbConnection, () => true, ['public']);
// 2. Convert to TypeScript code
const { file } = schemaToTypeScript(schema, 'camel');
console.log(file);Sources: drizzle-kit/src/serializer/pgSerializer.ts:968-1937, drizzle-kit/src/introspect-pg.ts:309-636