{"id":16528352,"url":"https://github.com/danvk/pg-to-ts","last_synced_at":"2025-04-06T05:16:47.367Z","repository":{"id":37035064,"uuid":"245477759","full_name":"danvk/pg-to-ts","owner":"danvk","description":" Generate TypeScript interface definitions from your Postgres schema","archived":false,"fork":false,"pushed_at":"2023-11-26T09:19:47.000Z","size":1500,"stargazers_count":114,"open_issues_count":17,"forks_count":18,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-30T03:06:19.190Z","etag":null,"topics":["postgresql","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/pg-to-ts","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/danvk.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-03-06T17:18:03.000Z","updated_at":"2025-02-26T23:36:20.000Z","dependencies_parsed_at":"2024-06-18T21:36:55.815Z","dependency_job_id":"bee0ff15-9c9a-4e73-9125-118c4f6f5766","html_url":"https://github.com/danvk/pg-to-ts","commit_stats":{"total_commits":271,"total_committers":18,"mean_commits":"15.055555555555555","dds":0.5645756457564576,"last_synced_commit":"d3e9b4cc05f04d0f6eb931e53d05d90311afb5e9"},"previous_names":[],"tags_count":41,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danvk%2Fpg-to-ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danvk%2Fpg-to-ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danvk%2Fpg-to-ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danvk%2Fpg-to-ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danvk","download_url":"https://codeload.github.com/danvk/pg-to-ts/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247436286,"owners_count":20938533,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["postgresql","typescript"],"created_at":"2024-10-11T17:39:50.422Z","updated_at":"2025-04-06T05:16:47.335Z","avatar_url":"https://github.com/danvk.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# pg-to-ts\n\n`pg-to-ts` generates TypeScript types that match your Postgres database schema.\nIt works by querying the Postgres metadata schema (`pg_catalog`) and generating\nequivalent TypeScript types, as well as some JavaScript values that can be\nhelpful for generating queries at runtime.\n\nUsage:\n\n    npm install pg-to-ts\n    pg-to-ts generate -c postgresql://user:pass@host/db -o dbschema.ts\n\nThe resulting file looks like:\n\n```ts\n// Table product\nexport interface Product {\n  id: string;\n  name: string;\n  description: string;\n  created_at: Date;\n}\nexport interface ProductInput {\n  id?: string;\n  name: string;\n  description: string;\n  created_at?: Date;\n}\nconst product = {\n  tableName: 'product',\n  columns: ['id', 'name', 'description', 'created_at'],\n  requiredForInsert: ['name', 'description'],\n} as const;\n\nexport interface TableTypes {\n  product: {\n    select: Product;\n    input: ProductInput;\n  };\n}\n\nexport const tables = {\n  product,\n};\n```\n\nThis gives you most of the types you need for static analysis and runtime.\n\nThis is a fork of [PYST/schemats][pyst-fork], which is a fork of [SweetIQ/schemats][orig-repo]. Compared to those projects, this fork:\n\n- Drops support for MySQL in favor of deeper support for Postgres.\n- Significantly modernizes the infrastructure and dependencies.\n- Adds a few new features (see below).\n\n## Schema Features\n\n### Comments\n\nIf you set a Postgres comment on a table or column:\n\n```sql\nCOMMENT ON TABLE product IS 'Table containing products';\nCOMMENT ON COLUMN product.name IS 'Human-readable product name';\n```\n\nThen these come out as JSDoc comments in the schema:\n\n```ts\n/** Table containing products */\nexport interface Product {\n  id: string;\n  /** Human-readable product name */\n  name: string;\n  description: string;\n  created_at: Date;\n}\n```\n\nThe TypeScript language service will surface these when it's helpful.\n\n### Dates as strings\n\nnode-postgres returns timestamp columns as JavaScript Date objects. This makes\na lot of sense, but it can lead to problems if you try to serialize them as\nJSON, which converts them to strings. This means that the serialized and de-\nserialized table types will be different.\n\nBy default `pg-to-ts` will put `Date` types in your schema file, but if you'd\nprefer strings, pass `--datesAsStrings`. Note that you'll be responsible for\nmaking sure that timestamps/dates really do come back as strings, not Date objects.\nSee \u003chttps://github.com/brianc/node-pg-types\u003e for details.\n\n### JSON types\n\nBy default, Postgres `json` and `jsonb` columns will be typed as `unknown`.\nThis is safe but not very precise, and it can make them cumbersome to work with.\nOftentimes you know what the type should be.\n\nTo tell `pg-to-ts` to use a specific TypeScript type for a `json` column, use\na JSDoc `@type` annotation:\n\n```sql\nALTER TABLE product ADD COLUMN metadata jsonb;\nCOMMENT ON COLUMN product.metadata is 'Additional information @type {ProductMetadata}';\n```\n\nOn its own, this simply acts as documentation. But if you also specify the\n`--jsonTypesFile` flag, these annotations get incorporated into the schema:\n\n    pg-to-ts generate ... --jsonTypesFile './db-types' -o dbschema.ts\n\nThen your `dbschema.ts` will look like:\n\n```ts\nimport {ProductMetadata} from './db-types';\n\ninterface Product {\n  id: string;\n  name: string;\n  description: string;\n  created_at: Date;\n  metadata: ProductMetadata | null;\n}\n```\n\nPresumably your `db-types.ts` file will either re-export this type from elsewhere:\n\n```ts\nexport {ProductMetadata} from './path/to/this-type';\n```\n\nor define it itself:\n\n```ts\nexport interface ProductMetadata {\n  year?: number;\n  designer?: string;\n  starRating?: number;\n}\n```\n\nNote that, on its own, TypeScript cannot enforce a schema on your `json`\ncolumns. For that, you'll want a tool like [postgres-json-schema][].\n\n\n### Prefix tableNames with their corresponding schemaName\n\n`--prefixWithSchemaNames`\n\nIt will prefix all exports with the schema name. i.e `schemaname_tablename`. This allows you to easily namespace your exports.\n\nIf the schema name is: maxi, then the following exports will be generated for you when using the `--prefixWithSchemaNames`:\n\n```ts\n// Table product\nexport interface MaxiProduct {\n  id: string;\n  name: string;\n  description: string;\n  created_at: Date;\n}\nexport interface MaxiProductInput {\n  id?: string;\n  name: string;\n  description: string;\n  created_at?: Date;\n}\nconst maxi_product = {\n  tableName: 'maxi.product',\n  columns: ['id', 'name', 'description', 'created_at'],\n  requiredForInsert: ['name', 'description'],\n} as const;\n\nexport interface TableTypes {\n  maxi_product: {\n    select: MaxiProduct;\n    input: MaxiProductInput;\n  };\n}\n\nexport const tables = {\n  maxi_product,\n};\n```\n\n## Command Line Usage\n\nThere are a few ways to control `pg-to-ts`:\n\n### Command line flags\n\n    pg-to-ts generate -c postgresql://user:pass@host/db -o dbschema.ts\n\n### JS / JSON file\n\n    pg-to-ts generate --config path/to/config.json\n    pg-to-ts generate --config  # defaults to pg-to-ts.json\n    cat pg-to-ts.json\n\nThe JSON file has configuration options as top-level keys:\n\n```json\n{\n  \"conn\": \"postgres://user@localhost:5432/postgres\",\n  \"output\": \"/tmp/cli-pg-to-ts-json.ts\"\n}\n```\n\n### Environment variables\n\nFlags may also be specified using environment variables prefixed with `PG_TO_TS`:\n\n    PG_TO_TS_CONN=postgres://user@localhost:5432/postgres\n    PG_TO_TS_OUTPUT=/tmp/cli-env.ts\n    pg-to-ts generate\n\n## Development Quickstart\n\nYou'll need a Postgres instance running to do most development work with pg-to-ts.\n\n    git clone https://github.com/danvk/pg-to-ts.git\n    cd pg-to-ts\n    yarn\n    yarn build\n\nYou can iterate using your own DB schema. Or, to load the test schema, run:\n\n    psql postgres://user:pass@host/postgres -a -f test/fixture/pg-to-ts.sql\n\nThen generate a `dbschema.ts` file by running:\n\n    node dist/cli.js generate -c postgresql://user:pass@host/db -o dbschema.ts\n\nYou can use `yarn build --watch` to run `tsc` in watch mode.\n\nTo run the unit tests:\n\n    yarn build\n    POSTGRES_URL=postgres://user@localhost:5432/postgres yarn test\n\nTo run ESLint:\n\n    yarn lint\n\nSee [SweetIQ/schemats][orig-repo] for the original README.\n\n[orig-repo]: https://github.com/SweetIQ/schemats\n[pyst-fork]: https://github.com/PSYT/schemats\n[postgres-json-schema]: https://github.com/gavinwahl/postgres-json-schema\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanvk%2Fpg-to-ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanvk%2Fpg-to-ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanvk%2Fpg-to-ts/lists"}