MCPcopy
hub / github.com/adelsz/pgtyped

github.com/adelsz/pgtyped @v2.4.3 sqlite

repository ↗ · DeepWiki ↗ · release v2.4.3 ↗
683 symbols 1,089 edges 69 files 5 documented · 1%
README

PgTyped

Version Actions Status Join the chat at https://gitter.im/pgtyped/community

PgTyped makes it possible to use raw SQL in TypeScript with guaranteed type-safety.
No need to map or translate your DB schema to TypeScript, PgTyped automatically generates types and interfaces for your SQL queries by using your running Postgres database as the source of type information.


Features:

  1. Automatically generates TS types for parameters/results of SQL queries of any complexity.
  2. Supports extracting and typing queries from both SQL and TS files.
  3. Generate query types as you write them, using watch mode.
  4. Useful parameter interpolation helpers for arrays and objects.
  5. No need to define your DB schema in TypeScript, your running DB is the live source of type data.
  6. Prevents SQL injections by not doing explicit parameter substitution. Instead, queries and parameters are sent separately to the DB driver, allowing parameter substitution to be safely done by the PostgreSQL server.
  7. Native ESM support. Runtime dependencies are also provided as CommonJS.

Documentation

Visit our documentation page at https://pgtyped.dev/

Getting started

  1. npm install -D @pgtyped/cli typescript (typescript is a required peer dependency for pgtyped)
  2. npm install @pgtyped/runtime (@pgtyped/runtime is the only required runtime dependency of pgtyped)
  3. Create a PgTyped config.json file.
  4. Run npx pgtyped -w -c config.json to start PgTyped in watch mode.

More info on getting started can be found in the Getting Started page. You can also refer to the example app for a preconfigured example.

Example

Lets save some queries in books.sql:

/* @name FindBookById */
SELECT * FROM books WHERE id = :bookId;

PgTyped parses the SQL file, extracting all queries and generating strictly typed TS queries in books.queries.ts:

/** Types generated for queries found in "books.sql" */

//...

/** 'FindBookById' parameters type */
export interface IFindBookByIdParams {
  bookId: number | null;
}

/** 'FindBookById' return type */
export interface IFindBookByIdResult {
  id: number;
  rank: number | null;
  name: string | null;
  author_id: number | null;
}

/**
 * Query generated from SQL:
 * SELECT * FROM books WHERE id = :bookId
 */
export const findBookById = new PreparedQuery<
  IFindBookByIdParams,
  IFindBookByIdResult
>(...);

Query findBookById is now statically typed, with types inferred from the PostgreSQL schema.
This generated query can be imported and executed as follows:

import { Client } from 'pg';
import { findBookById } from './books.queries';

export const client = new Client({
  host: 'localhost',
  user: 'test',
  password: 'example',
  database: 'test',
});

async function main() {
  await client.connect();
  const books = await findBookById.run(
    {
      bookId: 5,
    },
    client,
  );
  console.log(`Book name: ${books[0].name}`);
  await client.end();
}

main();

Resources

  1. Configuring pgTyped
  2. Writing queries in SQL files
  3. Advanced queries and parameter expansions in SQL files
  4. Writing queries in TS files
  5. Advanced queries and parameter expansions in TS files

Project state:

This project is being actively developed and its APIs might change. All issue reports, feature requests and PRs appreciated.

License

MIT

Copyright (c) 2019-present, Adel Salakh

Extension points exported contracts — how you extend this code

ICursor (Interface)
(no doc) [2 implementers]
packages/runtime/src/tag.ts
SQLParserListener (Interface)
(no doc) [1 implementers]
packages/parser/src/loader/sql/parser/SQLParserListener.ts
IGetUsersWithCommentsParams (Interface)
(no doc)
packages/example/src/users/sample.types.ts
TransformJob (Interface)
(no doc)
packages/cli/src/index.ts
NamedType (Interface)
(no doc)
packages/query/src/type.ts
IMessagePayload (Interface)
(no doc)
packages/wire/src/protocol.ts
ScalarParameter (Interface)
(no doc)
packages/runtime/src/preprocessor.ts
QueryParserListener (Interface)
(no doc) [1 implementers]
packages/parser/src/loader/typescript/parser/QueryParserListener.ts

Core symbols most depended-on inside this repo

processSQLQueryIR
called by 31
packages/runtime/src/preprocessor-sql.ts
run
called by 23
packages/cli/src/index.ts
processTSQueryAST
called by 22
packages/runtime/src/preprocessor-ts.ts
enterRule
called by 20
packages/parser/src/loader/sql/parser/SQLParser.ts
exitRule
called by 20
packages/parser/src/loader/sql/parser/SQLParser.ts
parseMessage
called by 17
packages/wire/src/protocol.ts
queryASTToIR
called by 16
packages/parser/src/loader/sql/index.ts
stringToType
called by 15
packages/cli/src/config.ts

Shape

Method 373
Interface 115
Function 92
Class 90
Enum 13

Languages

TypeScript100%

Modules by API surface

packages/parser/src/loader/sql/parser/SQLParser.ts223 symbols
packages/parser/src/loader/typescript/parser/QueryParser.ts135 symbols
packages/example/src/books/books.queries.ts32 symbols
packages/parser/src/loader/sql/index.ts28 symbols
packages/parser/src/loader/typescript/query.ts19 symbols
packages/runtime/src/tag.ts18 symbols
packages/query/src/actions.ts17 symbols
packages/wire/src/helpers.ts14 symbols
packages/cli/src/types.ts14 symbols
packages/cli/src/generator.ts14 symbols
packages/cli/src/typedSqlTagTransformer.ts12 symbols
packages/example/src/comments/comments.queries.ts11 symbols

Dependencies from manifests, versioned

@docusaurus/core2.3.1 · 1×
@docusaurus/preset-classic2.3.1 · 1×
@pgtyped/cli2.4.3 · 1×
@pgtyped/parser2.4.2 · 1×
@pgtyped/query2.4.2 · 1×
@pgtyped/runtime2.4.2 · 1×
@pgtyped/wire2.4.2 · 1×
@types/chalk2.2.0 · 1×
@types/debug4.1.4 · 1×
@types/fs-extra11.0.4 · 1×
@types/jest29.5.14 · 1×
@types/node22.0.0 · 1×

Datastores touched

postgresDatabase · 1 repos

For agents

$ claude mcp add pgtyped \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact