Sequelize TypeScript Generator
sequelize-typescript-generator is a utility that automates the creation of TypeScript models for the sequelize-typescript ORM, directly from an existing relational database schema. Currently at version 12.0.1, the library provides both a command-line interface (CLI) and a programmatic API for model generation. It supports a wide range of SQL databases including PostgreSQL, MySQL, MariaDB, SQL Server, and SQLite, and is tested against various versions of these databases. Its primary differentiation lies in its ability to parse an existing database schema, infer table structures, column types, and common associations (one-to-one, one-to-many, many-to-many), and then generate type-safe sequelize-typescript models, significantly reducing manual boilerplate and ensuring model-to-database consistency. While no explicit release cadence is documented, its consistent major version updates suggest active development, aiming to keep pace with sequelize and sequelize-typescript advancements. The library also offers features like strict mode generation, case transformation for column names, and options for including index annotations, making it a robust tool for projects using a database-first approach with TypeScript and Sequelize.
Common errors
-
Error: Cannot find module 'pg'\nRequire stack:\n- .../node_modules/sequelize-typescript-generator/dist/cli.js
cause The required database driver for the specified dialect is not installed in the project's `node_modules`.fixInstall the appropriate database driver for your chosen dialect. For PostgreSQL, run `npm install pg pg-hstore`. For MySQL, `npm install mysql2`, etc. -
Error: Command 'stg' not found.
cause The `stg` command (from a global install) is not in the system's PATH, or `npx` (for local install) is not available to execute it.fixIf using locally, ensure `npx` is installed globally (`npm install -g npx`) or execute with `node ./node_modules/.bin/stg`. If using globally, ensure `npm install -g sequelize-typescript-generator` completed successfully and your global npm bin directory is in your system's PATH. -
SequelizeConnectionError: connect ECONNREFUSED <DB_HOST>:<DB_PORT>
cause The generator failed to establish a connection to the database, likely due to incorrect host, port, credentials, or the database server being unavailable/inaccessible.fixVerify the database server is running, reachable from where the generator is executed, and that the provided `host`, `port`, `username`, `password`, and `database` credentials are correct and have appropriate network access. -
TypeError: (0 , sequelize_typescript_generator_1.generate) is not a function
cause Attempting to use a CommonJS `require()` statement or an incorrect import syntax for an ES module-first library, or a bundling issue.fixEnsure you are using ES module imports: `import { generate } from 'sequelize-typescript-generator';`. If using CommonJS in a hybrid project, you might need `const { generate } = await import('sequelize-typescript-generator');` or configure your build system for proper ESM resolution.
Warnings
- breaking This library declares TypeScript version `^5.0.4` as a peer dependency. Using older or incompatible TypeScript versions might lead to compilation errors or unexpected type inference issues, especially with advanced features or strict mode.
- gotcha The generator requires the appropriate database driver (e.g., `pg` for PostgreSQL, `mysql2` for MySQL) to be installed in your project. Failure to install the correct driver for your chosen dialect will result in runtime errors.
- gotcha When using `sequelize-typescript-generator` globally (`npm install -g`), automatic linting of generated models is not supported out-of-the-box. The `eslint` library does not support global plugins for this functionality.
- gotcha Generated models are a snapshot of your database schema at the time of generation. Any subsequent changes to your database schema (e.g., adding/removing columns, altering types, new tables) will *not* automatically update the generated models. You must re-run the generator to reflect these changes.
- gotcha While the generator attempts to infer common associations, complex relationships or non-standard naming conventions might not be fully captured. In such cases, you might need to manually define associations via the `--associations-file` option or manually adjust the generated models.
Install
-
npm install sequelize-typescript-generator -
yarn add sequelize-typescript-generator -
pnpm add sequelize-typescript-generator
Imports
- generate
const generate = require('sequelize-typescript-generator');import { generate } from 'sequelize-typescript-generator'; - GeneratorOptions
import type { GeneratorOptions } from 'sequelize-typescript-generator';
Quickstart
import { generate } from 'sequelize-typescript-generator';
import path from 'path';
import fs from 'fs';
async function runGenerator() {
const outputDir = path.resolve(__dirname, 'generated-models');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
try {
await generate({
dialect: 'postgres',
host: process.env.DB_HOST ?? 'localhost',
port: parseInt(process.env.DB_PORT ?? '5432', 10),
database: process.env.DB_NAME ?? 'your_database_name',
username: process.env.DB_USER ?? 'postgres',
password: process.env.DB_PASSWORD ?? '',
outDir: outputDir,
schema: process.env.DB_SCHEMA ?? 'public', // Optional, for Postgres
// tables: ['users', 'products'], // Optional: specify tables to generate
// skipTables: ['audit_logs'], // Optional: specify tables to skip
// indices: true, // Optional: include index annotations
// strict: true, // Optional: enable strict mode
// case: 'camel', // Optional: 'camel' | 'snake' | 'pascal'
// associationsFile: path.resolve(__dirname, 'associations.json'), // Optional: define custom associations
});
console.log('Sequelize TypeScript models generated successfully!');
} catch (error) {
console.error('Error generating models:', error);
process.exit(1);
}
}
runGenerator();