{"id":25940530,"url":"https://github.com/seralexeev/sqlc-typescript","last_synced_at":"2025-10-29T23:49:58.453Z","repository":{"id":276207482,"uuid":"927972087","full_name":"seralexeev/sqlc-typescript","owner":"seralexeev","description":"🛠️ A super lightweight TypeScript types generator that respects your laziness and love for raw SQL.","archived":false,"fork":false,"pushed_at":"2025-03-02T01:07:02.000Z","size":123055,"stargazers_count":35,"open_issues_count":2,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-13T05:39:25.159Z","etag":null,"topics":["postgres","sql","sqlc","typescript"],"latest_commit_sha":null,"homepage":"","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/seralexeev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"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":"2025-02-05T21:01:07.000Z","updated_at":"2025-03-02T01:07:05.000Z","dependencies_parsed_at":"2025-02-06T22:38:19.010Z","dependency_job_id":null,"html_url":"https://github.com/seralexeev/sqlc-typescript","commit_stats":null,"previous_names":["seralexeev/sqlc-typescript"],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seralexeev%2Fsqlc-typescript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seralexeev%2Fsqlc-typescript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seralexeev%2Fsqlc-typescript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seralexeev%2Fsqlc-typescript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/seralexeev","download_url":"https://codeload.github.com/seralexeev/sqlc-typescript/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248670506,"owners_count":21142897,"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":["postgres","sql","sqlc","typescript"],"created_at":"2025-03-04T05:17:11.271Z","updated_at":"2025-10-29T23:49:58.401Z","avatar_url":"https://github.com/seralexeev.png","language":"TypeScript","readme":"# \u003cimg width=\"34\" alt=\"typescript\" src=\"https://github.com/user-attachments/assets/a1239abb-ae71-480f-9842-98293587ae60\"\u003e sqlc-typescript\n\n\u003c!-- NPM Badges --\u003e\n\n[![npm version](https://img.shields.io/npm/v/sqlc-typescript.svg)](https://www.npmjs.com/package/sqlc-typescript)\n[![npm downloads](https://img.shields.io/npm/dm/sqlc-typescript.svg)](https://www.npmjs.com/package/sqlc-typescript)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![npm types](https://img.shields.io/npm/types/sqlc-typescript.svg)](https://www.npmjs.com/package/sqlc-typescript)\n[![Dependencies](https://img.shields.io/librariesio/release/npm/sqlc-typescript)](https://libraries.io/npm/sqlc-typescript)\n\n\u003c!-- GitHub Badges --\u003e\n\n[![GitHub stars](https://img.shields.io/github/stars/seralexeev/sqlc-typescript.svg)](https://github.com/seralexeev/sqlc-typescript)\n[![GitHub issues](https://img.shields.io/github/issues/seralexeev/sqlc-typescript.svg)](https://github.com/seralexeev/sqlc-typescript/issues)\n[![GitHub last commit](https://img.shields.io/github/last-commit/seralexeev/sqlc-typescript.svg)](https://github.com/seralexeev/sqlc-typescript/commits)\n[![Contributors](https://img.shields.io/github/contributors/seralexeev/sqlc-typescript)](https://github.com/seralexeev/sqlc-typescript/graphs/contributors)\n\n\u003c!-- CI/CD Badges --\u003e\n\n[![CI](https://github.com/seralexeev/sqlc-typescript/actions/workflows/manual-release.yml/badge.svg)](https://github.com/seralexeev/sqlc-typescript/actions/workflows/manual-release.yml)\n\nA super lightweight TypeScript types generator that respects your laziness and love for raw SQL.\n\nZero runtime dependencies, just types. This is just a super thin wrapper around [sqlc](https://sqlc.dev/) and a file generator - all the real magic is in **sqlc**. It just makes it more convenient to use in TypeScript projects.\n\n## 🏃 TLDR\n\n- `pg_dump --schema-only postgres://user:password@localhost:5432/database \u003e schema.sql` to dump your schema\n- Run `npx sqlc-typescript watch` (`src/**/*.ts` is default glob and `schema.sql` is default schema file)\n- Write SQL queries in your TypeScript files using the `/*sql*/` comment and `sqlc` function e.g.\n\n    ```typescript\n    const result = await sqlc(/*sql*/ `\n          SELECT customer_id, first_name, last_name\n          FROM customer \n          WHERE customer_id = @customer_id\n      `).exec(client, {\n        customer_id: 1,\n    });\n    ```\n\n- Import the generated `sqlc` function and get perfect types 🔥\n\n## 🚀 Demo\n\n\u003cimg alt=\"image\" src=\"https://github.com/user-attachments/assets/0556e61c-72ab-465e-86b7-3013e1b82c6f\" /\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eVideo\u003c/summary\u003e\n  \n  https://github.com/user-attachments/assets/dba59632-6c4c-48fe-80f0-da1514e2da1a\n\u003c/details\u003e\n\n## 🤔 Why?\n\nIf you're like me - you just want to write SQL, ship features and not deal with heavy abstractions or spend hours reading documentation (even if it's really good). That's exactly why this exists.\n\n### 🤯 The Problem\n\n- ORMs are complex and make you learn their quirks\n- SQL-like query builders still make you learn their syntax and requires rewriting existing queries to their format\n- Writing SQL in separate files is annoying\n- Maintaining function names for every query is tedious\n- Other tools require database connections for type inference (which isn't always accurate)\n\n### 🎯 The Solution\n\nWrite SQL directly in your TypeScript files, get perfect types, and ship faster. That's it.\n\n```typescript\n// Your SQL lives right in your code\nconst result = await sqlc(/*sql*/ `\n    SELECT \n        customer_id,\n        first_name,\n        last_name\n    FROM\n        customer \n    WHERE \n        customer_id = @customer_id\n`).exec(client, {\n    customer_id: 1,\n});\n\n// result: { customer_id: number, first_name: string | null, last_name: string }[]\n```\n\n## 🛠️ Installation\n\n```bash\n# Using npm\nnpm install sqlc-typescript\n\n# Using yarn\nyarn add sqlc-typescript\n\n# Using pnpm\npnpm add sqlc-typescript\n```\n\n## 📝 Configuration Options\n\nThe following configuration options can be set in your `sqlc.json` file:\n\n| Option      | Type                        | Default         | Description                                                                                                                                                                                                 |\n| ----------- | --------------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `schema`    | `string`                    | `\"schema.sql\"`  | Path to your SQL schema file, typically generated using `pg_dump --schema-only`. This file should contain your database schema definitions including tables, views, and types.                              |\n| `include`   | `string`                    | `\"src/**/*.ts\"` | Glob pattern for TypeScript files to scan for SQL queries. The generator will look for queries marked with `/*sql*/` in these files.                                                                        |\n| `output`    | `string`                    | `\"src/sqlc.ts\"` | Location where the generated TypeScript types file will be written. This file will contain all the type definitions and the `sqlc` function.                                                                |\n| `tmp_dir`   | `string`                    | `\".sqlc\"`       | Directory used for temporary files during type generation. This directory will contain intermediate files used by sqlc.                                                                                     |\n| `clear_tmp` | `boolean`                   | `true`          | Whether to remove the temporary directory after type generation is complete. Set to `false` if you need to inspect the intermediate files for debugging.                                                    |\n| `types`     | `{ [key: string]: string }` | `{}`            | Map of PostgreSQL types to TypeScript types. Use this to override the default type mappings for specific database types.                                                                                    |\n| `columns`   | `{ [key: string]: string }` | `{}`            | Map of specific column types to TypeScript types. This takes precedence over both default type mappings and `types` overrides. The key should be in the format `\"table.column\"` or `\"schema.table.column\"`. |\n| `imports`   | `string[]`                  | `[]`            | Array of import statements to include in the generated file. Use this when you need to import custom types used in your `types` or `columns` mappings.                                                      |\n\n### Example Configuration\n\n```json\n{\n    \"schema\": \"db/schema.sql\",\n    \"include\": \"src/**/*.{ts,tsx}\",\n    \"output\": \"src/generated/sqlc.ts\",\n    \"tmp_dir\": \".sqlc-temp\",\n    \"clear_tmp\": true,\n    \"types\": {\n        \"timestamptz\": \"DateTime\",\n        \"json\": \"JSONValue\"\n    },\n    \"columns\": {\n        \"users.id\": \"UUID\",\n        \"orders.status\": \"OrderStatus\"\n    },\n    \"imports\": [\n        \"import type { UUID } from '../types'\",\n        \"import type { OrderStatus } from '../db-types'\",\n        \"import type { JSONValue } from '../json-types'\"\n    ]\n}\n```\n\n## 💻 Usage\n\n1. Write your SQL queries in TypeScript files using the `/*sql*/` tag:\n\n```typescript\nimport { sqlc } from './sqlc';\n\n// Get customer details\nconst customer = await sqlc(/*sql*/ `\n    SELECT \n        customer_id,\n        first_name,\n        last_name,\n        email\n    FROM \n        customer \n    WHERE \n        customer_id = @customer_id\n`).exec(client, {\n    customer_id: '123e4567-e89b-12d3-a456-426614174000',\n});\n\n// Types are automatically inferred!\ncustomer[0].first_name; // string\ncustomer[0].email; // string | null\n```\n\n2. Run the generator:\n\n```bash\nnpx sqlc-typescript generate -c sqlc.json\n\n# Or watch mode\nnpx sqlc-typescript watch -c sqlc.json\n```\n\n## 🔧 How It Works Under The Hood\n\n1. **File Scanning**: The tool scans your TypeScript files for SQL queries marked with `/*sql*/`\n2. **Type Generation**: Uses [sqlc](https://github.com/sqlc-dev/sqlc) under the hood to analyze your SQL and generate types\n3. **Zero Runtime Overhead**: All the magic happens at build time - no runtime dependencies!\n\n### 🏷️ Why Tagged Templates Can't Be Used\n\nUnfortunately, we can't use tagged template literals like `` sql`SELECT * FROM users` `` for proper syntax highlighting. TypeScript template literals [can't be generic](https://github.com/microsoft/TypeScript/issues/33304), so we can use the `/*sql*/` comment approach instead. Your IDE or SQL plugin will still provide syntax highlighting!\n\n### 🔍 Comparison with Other Tools\n\n- [pgTyped](https://github.com/adelsz/pgtyped): Requires separate SQL files and function imports. It uses PostgreSQL wire protocol for type inference which requires a database connection and can't handle nullability well.\n- [Prisma TypedSQL](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/typedsql): SQL files are separate and require function imports and it's Prisma 🫠.\n- [SafeQL](https://github.com/ts-safeql/safeql): Great tool but requires ESLint and database connection for type inference.\n- [Drizzle](https://orm.drizzle.team/): SQL-like a great query builder but it's not just SQL. I don't want to learn another syntax even if it's very close to SQL. I can't copy-past my queries from psql back and forth.\n\nThe key difference: We use sqlc's SQL parser instead of PostgreSQL wire protocol for type inference, which means:\n\n- More accurate types\n- Better nullability inference for complex joins\n- No database connection needed\n- Just need a schema dump (`pg_dump --schema-only`)\n\n## 💅 SQL Formatting\n\nYou can use Prettier with SQL plugins to format your queries inside the template literals.\n\n- https://github.com/un-ts/prettier\n- https://github.com/Sec-ant/prettier-plugin-embed\n\n```typescript\n// This will be properly formatted\nsqlc(/*sql*/ `\n    SELECT \n        id, \n        name,\n        email \n    FROM \n        users \n    WHERE \n        active = true\n`).exec(client);\n```\n\n## 🛣️ Roadmap\n\n- Support for all sqlc features and database support beyond PostgreSQL\n- Automatic result unflattening using column aliases\n\n## ⚠️ Limitations\n\n- PostgreSQL only (for now)\n- Queries must be statically analyzable (no dynamic SQL) which is good and bad at the same time\n- All queries must be called using `sqlc` function until TypeScript supports generic template literals\n\n## 🙏 Credits\n\nBig thanks to:\n\n- [sqlc](https://github.com/sqlc-dev/sqlc) team for the amazing SQL parser and type generator\n- Other projects like pgTyped, Prisma, and SafeQL for inspiration\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseralexeev%2Fsqlc-typescript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fseralexeev%2Fsqlc-typescript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseralexeev%2Fsqlc-typescript/lists"}