https://github.com/aldis-ameriks/pg-typegen
Generate TypeScript type definitions from Postgres database
https://github.com/aldis-ameriks/pg-typegen
codegen database pg-typegen postgres schema schema-typegen typegen types typescript
Last synced: 10 months ago
JSON representation
Generate TypeScript type definitions from Postgres database
- Host: GitHub
- URL: https://github.com/aldis-ameriks/pg-typegen
- Owner: aldis-ameriks
- License: mit
- Created: 2020-07-11T12:30:32.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2025-06-02T07:53:45.000Z (about 1 year ago)
- Last Synced: 2025-07-09T05:06:00.901Z (12 months ago)
- Topics: codegen, database, pg-typegen, postgres, schema, schema-typegen, typegen, types, typescript
- Language: JavaScript
- Homepage:
- Size: 258 KB
- Stars: 7
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
pg-typegen
> Generate TypeScript type definitions from Postgres database.
## Install
```sh
$ npm install -D pg-typegen
# or
$ yarn add -D pg-typegen
# or
$ pnpm add -D pg-typegen
```
## Usage
```
Usage: pg-typegen [options]
Options:
-V, --version output the version number
-f, --suffix suffix to append to generated table type, e.g. item -> ItemEntity (default: "Entity")
-s, --schema schema (default: "public")
-h, --header header content (default: "")
-o, --output file output path (default: "stdout")
-e, --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 types for views and materialized views (default: false)
--help display help for command
Example:
$ pg-typegen -o ./entities.ts postgres://username:password@localhost:5432/database
```
Given database table
```sql
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
```ts
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](https://github.com/brianc/node-postgres) 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
```sql
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
```ts
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.
```ts
const user: UserInsertEntity = { name: 'foo' }
knex('users').insert(user)
```
### Running from code
```ts
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
```sh
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](https://github.com/aldis-ameriks).
This project is [MIT](https://github.com/aldis-ameriks/pg-typegen/blob/master/LICENSE) licensed.