Schemats
Schemats is a command-line interface (CLI) tool that automatically generates TypeScript interface definitions directly from existing SQL database schemas. It supports PostgreSQL and MySQL databases, allowing developers to ensure static type checking and autocompletion for database query results within TypeScript applications. The current stable version is 3.0.5, with major version updates occurring when significant architectural changes or dependency upgrades necessitate breaking changes to its API or CLI. Its primary differentiation lies in generating types directly from the live database schema, which helps keep type definitions synchronized with the actual database structure without manual intervention, supporting a 'database-first' approach to type safety in data access layers. It can generate types for individual tables or an entire schema and supports configuration via a JSON file.
Common errors
-
Error: self-signed certificate in certificate chain
cause Occurs when connecting to a PostgreSQL database with SSL enabled and a self-signed certificate, without explicitly trusting it.fixFor development, you can disable SSL verification by adding `?ssl=false` to your PostgreSQL connection string (`-c postgres://user:pass@host:port/db?ssl=false`). For production, properly configure SSL certificates or set `PGSSLMODE=no-verify` in your environment (though this is less secure). -
Error: Command failed with exit code 1
cause Generic error often indicating an issue with database connection parameters, insufficient permissions, or an incorrectly formatted connection string.fixDouble-check your database connection string for correctness (username, password, host, port, database name). Verify that the database server is running and accessible from where you're running `schemats`. Ensure the provided user has sufficient permissions to access the schema and tables you are trying to generate types for. -
No tables or schemas were specified for type generation. Please specify a table (-t) or schema (-s).
cause The `schemats generate` command was run without specifying either a target table (`-t`) or a target schema (`-s`), and no `schemats.json` was found to provide these defaults.fixSpecify the `-t <table_name>` argument to generate types for a single table, or `-s <schema_name>` to generate types for all tables in a specific schema. If you intend to generate all tables in the default 'public' schema, you can usually omit `-t` and `-s`, but ensure your connection string points to the correct database and the default behavior is understood.
Warnings
- breaking Version 3.0.0 introduced significant breaking changes. The project underwent a full TypeScript rewrite and a change in maintainership (from SweetIQ to devteck-io). This included a refactor of the internal programmatic API and updates to CLI argument parsing.
- breaking The `mysql` dependency was replaced by `mysql2` in version 3.0.0 for improved compatibility and features. Projects relying on `schemats` for MySQL type generation must ensure `mysql2` is installed and the connection string is compatible.
- gotcha Default type mappings from SQL to TypeScript (e.g., `TIMESTAMP` to `Date`, `TEXT` to `string`) might change between major versions or be configurable. Always verify the generated types align with your expected TypeScript representations, especially for complex or custom SQL types.
- gotcha When using `schemats.json` for configuration, ensure the file is in the current working directory where the `schemats generate` command is executed, or specify its path explicitly. Misplaced config files will lead to default behavior or errors.
Install
-
npm install schemats-v2 -
yarn add schemats-v2 -
pnpm add schemats-v2
Imports
- generateSchema
import { generateSchema } from 'schemats';import { generateSchema } from 'schemats/lib/typescript'; - Config
import { Config } from 'schemats';import { Config } from 'schemats/lib/config'; - Schemats CLI
schemats generate -c postgres://user@host/db -o types.ts
Quickstart
npm install -g schemats
# PostgreSQL example: Generate types for the 'users' table from a local PostgreSQL database
schemats generate -c postgres://postgres:password@localhost:5432/mydatabase -t users -o src/database/types/user.ts
# MySQL example: Generate types for all tables in the 'public' schema from a local MySQL database
schemats generate -c mysql://root:password@localhost:3306/mydatabase -s public -o src/database/types/all.ts
// Example of how to use the generated types in your application
// Assuming the generated file looks like:
// export interface Users { id: number; username: string; last_logon: Date; }
import * as dbTypes from './src/database/types/user';
interface MyUserRow extends dbTypes.Users {
// Add any application-specific fields or methods if needed
}
// Example usage with a database client (e.g., pg-promise, knex, or direct pg)
async function getUserById(id: number): Promise<MyUserRow | null> {
// This is illustrative; actual DB query logic would go here
const result: dbTypes.Users[] = await Promise.resolve([{ id: 1, username: 'testuser', password: 'hashedpassword', last_logon: new Date() }]);
return result.length > 0 ? result[0] : null;
}