npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pg-typegen

v3.9.0

Published

Generate TypeScript type definitions from Postgres database

Downloads

261

Readme

Generate TypeScript type definitions from Postgres database.

Install

$ npm install -D pg-typegen
# or
$ yarn add -D pg-typegen
# or
$ pnpm add -D pg-typegen

Usage

Usage: pg-typegen [options] <connection>

Options:
  -V, --version              output the version number
  -f, --suffix  <suffix>     suffix to append to generated table type, e.g. item -> ItemEntity (default: "Entity")
  -s, --schema  <schema>     schema (default: "public")
  -h, --header  <header>     header content (default: "")
  -o, --output  <output>     file output path (default: "stdout")
  -e, --exclude <exclude>    excluded tables and enums as comma separated string e.g. knex_migrations,knex_migrations_lock (default: [])
  --type                     use type definitions instead of interfaces in generated output (default: false)
  --semicolons               use semicolons in generated types (default: false)
  --ssl                      use ssl (default: false)
  --optionals                use optionals "?" instead of null (default: false)
  --comments                 generate table and column comments (default: false)
  --pascal-enums             transform enum keys to pascal case (default: false)
  --bigint                   use bigint for int8 types instead of strings (default: false)
  --date-as-string           use string for date types instead of javascript Date object (default: false)
  --insert-types             generate separate insert types with optional fields for columns allowing NULL value or having default values (default: false)
  --table-names              generate string literal type with all table names (default: false)
  --view-names               generate string literal type with all view names (default: false)
  --help                     display help for command

Example:
  $ pg-typegen -o ./entities.ts postgres://username:password@localhost:5432/database

Given database table

CREATE TYPE user_state AS ENUM (
  'asleep',
  'awake'
);

CREATE TABLE users (
    id int4 NOT NULL,
    name varchar(255),
    state user_state,
    is_enabled bool NOT NULL DEFAULT FALSE
);

Running pg-typegen -o ./entities.ts postgres://username:password@localhost:5432/database Will generate the following type definitions

enum UserState {
  asleep = 'asleep',
  awake = 'awake'
}

interface UserEntity {
  id: number;
  name: string | null;
  state: UserState | null;
  is_enabled: boolean;
}

By default, the types will be generated based on how pg returns the values.

Insert types

To simplify database inserts, separate types can be generated with optional values where NULL is allowed or default values for column exist in postgres.

Given database table

CREATE TYPE user_state AS ENUM (
  'asleep',
  'awake'
);

CREATE TABLE users (
    id serial4 PRIMARY KEY,
    name varchar(255) NOT NULL,
    state user_state,
    is_enabled bool NOT NULL DEFAULT FALSE
);

Running pg-typegen -o ./entities.ts --insert-types postgres://username:password@localhost:5432/database Will generate the following type definitions

enum UserState {
  asleep = 'asleep',
  awake = 'awake'
}

interface UserEntity {
  id: number;
  name: string;
  state: UserState | null;
  is_enabled: boolean;
}

interface UserInsertEntity {
  id?: number;
  name: string;
  state?: UserState | null;
  is_enabled?: boolean;
}

Which should allow working with insert objects without having to define all optional and nullable fields.

const user: UserInsertEntity = { name: 'foo' }
knex<UserInsertEntity>('users').insert(user)

Running from code

import { join } from 'path'
import generate from 'pg-typegen'
;(async () => {
  const output = join(__dirname, 'entities.ts')
  await generate({ connection: 'postgres://username:password@localhost:5432/database', output })
})()

Loading database config

from .env file

export $(grep -v '^#' .env | xargs) && pg-typegen -o ./entities.ts postgres://$DB_USERNAME:$DB_PASSWORD@$DB_HOST:$DB_PORT/$DB_NAME

from json file

pg-typegen -o ./entities.ts postgres://$(jq -r '.DB.USERNAME' config.json):$(jq -r '.DB.PASSWORD' config.json)@$(jq -r '.DB.HOST' config.json):$(jq -r '.DB.PORT' config.json)/$(jq -r '.DB.NAME' config.json)

Run tests

docker-compose up -d
npm test

Use RECREATE_DATABASE=true npm test when running tests for the first time

Contributing

Contributions, issues and feature requests are welcome!

License

Copyright © 2020 Aldis Ameriks. This project is MIT licensed.