Skip to content

blacksmoke26/posquelize

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Posquelize: PostgreSQL to Sequelize Generator

Automatically generate SequelizeJS minimal application via the command line.

Overview

Posquelize is a powerful CLI tool that automates the generation of Sequelize applications from PostgreSQL databases. It connects directly to your PostgreSQL instance, analyzes the database schema, and produces production-ready TypeScript boilerplate with comprehensive type definitions.

Key Features

Core Functionality

  • βœ… Complete Model Generation: Creates Sequelize models, repositories, and TypeScript type definitions
  • πŸ”„ Comprehensive Migration Support: Generates migrations for tables, functions, domains, views, triggers, indexes, and keys
  • πŸ“Š Advanced Type Support: Handles custom user-defined types with automatic conversions
  • πŸ“š Multi-Schema Support: Seamlessly handle multiple database schemas with efficient processing and organization.
  • ⚑ Visual Documentation: Creates database ER diagrams in DBML
  • πŸš€ Selective Generation: Filter by schemas or tables for targeted code generation
  • πŸ” Smart Relationship Detection: Identifies and configures table relationships and associations
  • πŸ“ Rich Type Definitions: Generates TypeScript interfaces, enums, and JSONB prototypes
  • 🎯 Production-Ready Boilerplate: Creates minimal but complete application structure
  • πŸ› οΈ Enhanced Model Options: Configurable model properties including timestamps, paranoid mode
  • πŸ”§ Advanced Migration Control: Granular control over migration generation with selective inclusion/exclusion options
  • πŸ“‹ JSON/JSONB Support: Automatically detects and generates TypeScript interfaces from column defaults or values, ensuring proper type safety for structured data.
  • πŸ—οΈ Composite Type Handling: Support for PostgreSQL composite types with automatic TypeScript interface generation

Developer Experience

  • πŸ” Secure Authentication: Interactive password prompts to avoid sensitive data in command history
  • πŸ“ Flexible Output: Configurable output directory and Sequelize directory structure
  • 🧹 Clean Generation: Automatic directory cleanup with --clean
  • 🎨 Template Customization: Support for custom output templates (upcoming)
  • βš™οΈ Configuration Files: Advanced configuration via posquelize.config.js for complex setups
  • πŸš€ Programmatic API: Full TypeScript API for integration into build pipelines and custom tools

Quick Start

Installation

npm install -g posquelize   # for NPM
pnpm add -g posquelize      # for PNPM
yarn global add posquelize  # for Yarn

Basic Usage

posquelize -h localhost -u postgres -d myapp_db -x

For advanced usage and a complete list of all available options, run:

posquelize --help

Configuration Options

Required Parameters

Option Description Example
πŸ—„οΈ -d, --database <name> Target database name myapp_db
πŸ‘€ -u, --user <username> Database username postgres
πŸ” -x, --password <password> Database password (or omit for prompt) mypassword

Optional Parameters

Option Description Default
🌐 -h, --host <address> IP/Hostname for the database localhost
πŸ”Œ -p, --port <port> Database connection port 5432
πŸ“ -o, --output <directory> Output directory path ./myapp
πŸ“‚ -n, --dirname <directory> Sequelize subdirectory name database
βš™οΈ --use-config Load posquelize.config.js configuration file from current directory. false
πŸ“š --schemas <schemas> Specific schemas to process (comma-separated) -
πŸ“‹ --tables <tables> Specific tables to generate (comma-separated) -
🧹 --clean Clean output directory before generation false
πŸ“Š --no-diagram Skip DBML ER diagram generation false
πŸ“‹ --no-migrations Skip migration files generation false
πŸ“¦ --no-repositories Skip repository files generation false
🏷️ --no-enums Use alternative types (literal / union) instead of enum false
πŸ“‹ --no-null-type Omit null in type declaration for nullable column false
🎨 --extract-templates Extract template files into the current directory for customization false

Usage Examples

Interactive Password Prompt

posquelize -h localhost -u postgres -d myapp_db -x

Schema-Specific Generation

posquelize -h localhost -u postgres -d myapp_db -x --schemas public,auth

Table-Specific Generation

posquelize -h localhost -u postgres -d myapp_db -x --tables users,posts,comments

Custom Output with Clean Build

posquelize -h localhost -u postgres -d myapp_db -x -o ./my-sequelize-app --clean

Security Best Practices

⚠️ Security Alert: Never include passwords directly in command-line arguments or scripts. Posquelize provides an interactive password prompt when the -x flag is used without a value, ensuring credentials don't appear in shell history or process lists.

Generated Project Structure

The tool generates a complete application structure with:

  • TypeScript Models: Fully typed models with validations
  • Migration Scripts: Version-controlled database schema changes
  • Type Definitions: Comprehensive TypeScript interfaces and types
  • Relationship Maps: Automatically configured associations
  • Repository Pattern: Abstraction layer for data access
<output-directory>/
β”‚   πŸ“„ .env                                          # Environment variables
β”‚   πŸ“„ .gitignore                                    # Git ignore rules
β”‚   βš™οΈ .sequelizerc                                  # Sequelize configuration
β”‚   πŸ“¦ package.json                                  # Dependencies and scripts
β”‚   πŸ“– README.md                                     # Project documentation
β”‚   βš™οΈ tsconfig.json                                 # TypeScript configuration
└───src/
    β”‚   πŸš€ server.ts                                 # Application entry point
    └───<sequelize-directory>/                        # Default to `database`
        β”‚    πŸ”— instance.ts                          # Database connection
        β”œβ”€β”€β”€base/                                     # Base classes
        β”‚   β”œβ”€β”€ πŸ“ ModelBase.ts
        β”‚   └── πŸ“ RepositoryBase.ts
        β”œβ”€β”€β”€config/                                  # Configuration files
        β”‚   └── βš™οΈ config.js
        β”œβ”€β”€β”€diagrams/                                # Database documentation
        β”‚   β”œβ”€β”€ πŸ“Š database.dbml
        β”‚   └── πŸ“– README.md
        β”œβ”€β”€ models/                                  # Sequelize model files
        β”‚   β”œβ”€β”€ πŸ“ User.ts
        β”‚   β”œβ”€β”€ πŸ“ Post.ts
        β”‚   └── ...                                  # Generated model files
        β”œβ”€β”€ migrations/                              # Sequelize migration files
        β”‚   β”œβ”€β”€ πŸ“ 20251101000000-create-users.js
        β”‚   β”œβ”€β”€ πŸ“ 20251101000001-create-posts.js
        β”‚   └── ...                                  # Generated migration files
        β”œβ”€β”€ repositories/                            # Repository pattern implementations
        β”‚   β”œβ”€β”€ πŸ“ UserRepository.ts
        β”‚   β”œβ”€β”€ πŸ“ PostRepository.ts
        β”‚   └── ...                                  # Generated repository files
        β”œβ”€β”€ types/                                   # TypeScript type definitions
        β”œβ”€β”€β”€seeders/                                 # Database seeders
        └───typings/                                 # Type definitions
            β””β”€β”€πŸ“ models.d.ts

Configuration File

To use a configuration file for more complex setups:

  1. Create a posquelize.config.js file in your project's root directory.

    Note: If a config file doesn't exist, will be created in the current directory.

  2. Configure your options using the JavaScript configuration object.

  3. Run the generator with the --use-config.

posquelize --use-config

Available configuration via posquelize.config.js file:

module.exports = {
  connection: {             // Database connection configuration
    host: 'localhost',      // Host name / IP
    username: 'postgres',   // Username for database
    password: '<password>', // The password
    database: 'test_db',    // The database name
    port: 5432,             // The port to connect
  },

  outputDir: __dirname + '/my_app', // Output directory
  cleanRootDir: true,       // Clean output directory before generation
  dirname: 'db',            // Sequelize subdirectory name

  schemas: [/*'public'*/],  // Specific schemas to process
  tables:  [/*'tags', 'products'*/], // Specific tables to generate

  // Migration configuration
  migrations: {
    indexes: true,    // Generate index migrations
    seeders: true,    // Generate seeder files
    functions: true,  // Generate function migrations
    domains: true,    // Generate domain migrations
    composites: true, // Generate composite type migrations
    tables: true,     // Generate table migrations
    views: true,      // Generate view migrations
    triggers: true,   // Generate trigger migrations
    foreignKeys: true // Generate foreign key migrations
  },

  diagram: false,       // Skip DBML diagram generation
  repositories: false,  // Skip repository file generation

  generator: {
    model: {
      addNullTypeForNullable: true, // Controls whether nullable typed property
      replaceEnumsWithTypes: false, // Replace enum with String Union types
    },
    // Configurable enums for table columns, (generate enums instead of plain value)
    enums: [{
      path: 'public.products.status', // schemaName.tableName.columnName
      values: {active: 10, inactive: 5, deleted: 0, suspended: 3}, // key:value map
      defaultValue: 10, // Default value to be set in init -> options -> column definition
    }, {
      path: 'public.products.visibility',
      values: ['public', 'private'], // list of values
      // defaultValue: 'private', // Default Value is set in DDL
    }],
  },
  
  // Path to directory containing custom templates for code generation
  templatesDir: __dirname + '/templates',
};

Programmatic API

The Posquelize programmatic API allows you to integrate database generation directly into your TypeScript/JavaScript applications. This provides greater flexibility and automation capabilities compared to using the CLI alone.

Basic Usage

import { PosquelizeGenerator } from 'posquelize';

// Define your PostgreSQL connection string
// Format: postgresql://<user>:<pass>@<host>:<port>/<database>
const connectionString = 'postgresql://user:pass@localhost:5432/test_db';

// Initialize the generator with connection string and output path
const posquelize = PosquelizeGenerator.create(connectionString, __dirname + '/myapp', {
  cleanRootDir: true, // Clean output directory before generation

  // other configuration goes here
});

// Execute the generation process
await posquelize.generate();

Advanced Configuration

The programmatic API supports all configuration options available in the CLI tool, allowing for fine-grained control over the generation process:

import { PosquelizeGenerator, GeneratorOptions } from 'posquelize';

const options: GeneratorOptions = {
  cleanRootDir: true,
  dirname: 'database',
  schemas: ['public', 'auth'],
  tables: ['users', 'posts', 'comments'],
  migrations: {
    tables: true,
    foreignKeys: true,
    indexes: false
  },
  diagram: false,
  repositories: true
};

const posquelize = PosquelizeGenerator.create(connectionString, './output', options);

await posquelize.generate();

Error Handling

Always wrap the generation process in try-catch blocks to handle potential connection or generation errors:

try {
  await posquelize.generate();
  console.log('Database generation completed successfully!');
} catch (error) {
  console.error('Generation failed:', error.message);
  // Handle error appropriately for your application
}

Contributing to Posquelize

  1. Fork the project repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Implement your changes with proper testing
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Submit a Pull Request for review

Tech Stack & Tools

  • Machine: Legion Pro 7 16IAX10H
  • Development Environment: Windows 11
  • Primary IDE: JetBrains PhpStorm
  • Alternative Editor: Zed with AI assistance
  • AI Tools: Qwen, Ollama (GLM 4.6, Qwen 3 Coder)

Acknowledgments

This project builds upon concepts and implementations from Sequelize Models Generator, with significant enhancements for TypeScript support and application generation.

Inspirations

This project draws inspiration from innovative tools in the Sequelize ecosystem:

  • Sequelize UI - A comprehensive web-based solution for generating TypeScript Sequelize code with flexible database configurations and customizable outputs.

  • Sequelize-Auto - A command-line utility that automates the creation of Sequelize models by analyzing existing database structures.

License

Posquelize is released under the MIT License. See LICENSE file for details.

About

Automatic Sequelize application generation from PostgreSQL database

Resources

Stars

Watchers

Forks

Packages

No packages published