{"id":17872,"library":"pgzod","title":"pgzod - PostgreSQL to Zod Schema Generator","description":"pgzod is a command-line utility for generating TypeScript-first Zod schemas and types directly from a live PostgreSQL database schema. It aims to synchronize your application's data validation and typing with your database structure, reducing manual effort and potential mismatches. The current stable version is 3.3.0, with minor and patch releases occurring regularly based on feature additions and bug fixes. Key differentiators include its focused integration with PostgreSQL, leveraging Zod for robust validation, and the ability to define different 'strategies' (like `write` or `readwrite`) for schema generation based on usage context. While primarily a CLI tool, it also offers a programmatic API for direct integration into Node.js applications, supporting database connection details via environment variables or configuration objects, making it suitable for both local development and CI/CD pipelines.","status":"active","version":"3.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/guzmonne/pgzod","tags":["javascript","typescript","postgresql","zod","schema"],"install":[{"cmd":"npm install pgzod","lang":"bash","label":"npm"},{"cmd":"yarn add pgzod","lang":"bash","label":"yarn"},{"cmd":"pnpm add pgzod","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required to connect to PostgreSQL databases and query schema information.","package":"pg","optional":false},{"reason":"The core schema declaration and validation library that pgzod generates schemas for, making it a fundamental peer dependency for the generated output.","package":"zod","optional":false}],"imports":[{"note":"This is the primary function for programmatic schema generation. ESM import is preferred.","wrong":"const generateZodSchemas = require('pgzod');","symbol":"generateZodSchemas","correct":"import { generateZodSchemas } from 'pgzod';"},{"note":"The type definition for the configuration object passed to `generateZodSchemas`. Use `import type` for type-only imports.","wrong":"import { Config } from 'pgzod';","symbol":"Config","correct":"import type { Config } from 'pgzod';"},{"note":"Utility function to retrieve the current pgzod configuration, typically for CLI usage or advanced programmatic setups.","wrong":"import getConfig from 'pgzod';","symbol":"getConfig","correct":"import { getConfig } from 'pgzod';"}],"quickstart":{"code":"import { generateZodSchemas, type Config } from 'pgzod';\nimport * as path from 'path';\nimport * as fs from 'fs'; // Required for fs.existsSync to check output, but not strictly for pgzod itself.\n\nasync function main() {\n  // Ensure your .env file or environment variables are set:\n  // PGHOST=localhost\n  // PGPORT=5432\n  // PGUSER=postgres\n  // PGPASSWORD=mysecretpassword\n  // PGDATABASE=your_database_name\n  // PGSCHEMA=public\n\n  const outputFilePath = path.join(__dirname, 'generated_schemas.ts');\n\n  const config: Config = {\n    host: process.env.PGHOST ?? 'localhost',\n    port: parseInt(process.env.PGPORT ?? '5432', 10),\n    user: process.env.PGUSER ?? 'postgres',\n    password: process.env.PGPASSWORD ?? 'mysecretpassword',\n    database: process.env.PGDATABASE ?? 'your_database_name',\n    schema: process.env.PGSCHEMA ?? 'public',\n    output: outputFilePath,\n    strategy: 'readwrite', // Options: 'write' or 'readwrite'\n    // customZodTypes: { // Example for mapping custom PostgreSQL types\n    //   'jsonb': 'z.any()',\n    // },\n  };\n\n  try {\n    console.log(`Attempting to generate Zod schemas from DB '${config.database}' (schema: '${config.schema}')...`);\n    await generateZodSchemas(config);\n    console.log(`Successfully generated Zod schemas to: ${outputFilePath}`);\n\n    // To demonstrate usage of generated schemas (requires a 'user' table in your DB)\n    // if (fs.existsSync(outputFilePath)) {\n    //   const { UserReadSchema } = await import(outputFilePath); // Adjust based on your table names\n    //   console.log(\"Example UserReadSchema shape:\", UserReadSchema.shape);\n    // }\n\n  } catch (error) {\n    console.error(\"Failed to generate Zod schemas:\", error);\n    process.exit(1);\n  }\n}\n\nmain();","lang":"typescript","description":"Demonstrates how to programmatically generate Zod schemas from a PostgreSQL database using `pgzod`, connecting via environment variables and specifying an output path and generation strategy. This script requires environment variables for PostgreSQL connection details."},"warnings":[{"fix":"Review your database schema for tables with generated columns and inspect the newly generated Zod schemas. Ensure your application's validation logic accommodates these changes.","message":"pgzod v3.0.0 introduced support for generated columns. While this is a feature, it represents a significant change in how schemas are processed and might affect existing generated schemas if not handled, particularly if you were previously working around the lack of support.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Inspect your Zod schemas related to foreign keys generated by pgzod v3.0.1 or newer. Adjust your application's validation logic if you relied on foreign keys being implicitly required, or customize `customZodTypes` if specific foreign keys must remain required.","message":"In v3.0.1, pgzod changed its default behavior, no longer marking foreign keys as strictly required. This alters the generated Zod schema for relationships, potentially making fields that were implicitly required optional.","severity":"breaking","affected_versions":">=3.0.1"},{"fix":"Upgrade your Node.js environment to version 14 or higher to ensure compatibility and receive library updates.","message":"Node.js v12 support was officially dropped in pgzod v2.1.1. Users on older Node.js versions must upgrade to at least Node.js 14 (or newer supported LTS versions) to use pgzod v2.1.1 and beyond.","severity":"breaking","affected_versions":">=2.1.1"},{"fix":"When using the CLI, specify your schema with `--schema your_schema_name`. Programmatically, set the `schema` property in the `Config` object (e.g., `schema: 'your_schema_name'`).","message":"By default, pgzod will only process tables within the 'public' schema of your PostgreSQL database. If your tables are organized into a different schema (e.g., 'app', 'private'), pgzod will not find them without explicit instruction.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Verify that `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, and `PGDATABASE` environment variables (or corresponding command-line options/config properties) are correct. Ensure the database server is running and accessible from the machine where pgzod is executed, and check for any firewall restrictions.","cause":"The pgzod CLI tool or programmatic function failed to establish a connection to the PostgreSQL database. This typically indicates incorrect connection details or a network issue.","error":"Error: connect ECONNREFUSED <DB_HOST>:<DB_PORT>"},{"fix":"Double-check the provided schema name for typos. Confirm that the specified schema (`--schema` option or `Config.schema`) actually contains tables you intend to generate Zod schemas for.","cause":"pgzod connected to the database but could not find any tables within the specified PostgreSQL schema. This can occur if the schema name is incorrect or the schema is genuinely empty.","error":"No tables found in the provided schema: 'your_schema_name'"},{"fix":"Review the database schema and the corresponding generated Zod schema (`generated_schemas.ts`). Ensure your input data matches the expected types, required fields, and constraints. Pay particular attention to changes in pgzod v3.0.1 regarding foreign key optionality, which might require adjustments to your input data or validation logic.","cause":"Data being validated against a pgzod-generated Zod schema does not conform to the schema's defined rules. This often points to a mismatch between the current database schema, the generated Zod schema, and the input data, possibly after a database migration or due to misinterpretation of types.","error":"ZodError: Invalid input (when validating data with pgzod-generated schemas)"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}