Schemats

3.0.5 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install Schemats globally, generate TypeScript interfaces from a PostgreSQL or MySQL database schema using CLI commands, and illustrates basic usage of the generated types within a TypeScript application.

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;
}

view raw JSON →