Getting Started with PgTyped: A Guide to Type-Safe SQL in TypeScript

Aug 17, 2024 | Programming

PgTyped is a powerful tool that allows developers to use raw SQL within TypeScript while ensuring guaranteed type safety. With PgTyped, you do not have to worry about manually mapping or translating your database schema to TypeScript, as it automatically generates types and interfaces based on your running Postgres database. In this blog post, we will walk you through the steps to get started with PgTyped, while also troubleshooting common issues.

Why Use PgTyped?

PgTyped is designed to simplify your development process by:

  • Automatically generating TypeScript types for SQL queries of any complexity.
  • Supporting extraction and typing from both SQL and TypeScript files.
  • Providing live updates to query types in watch mode.
  • Preventing SQL injections by managing parameter substitutions safely.
  • Offering both native ES Module support and CommonJS dependencies.

How to Get Started

Let’s dive into setting up PgTyped in your project:

  1. Install Dependencies: Run the following command to install PgTyped and TypeScript.
  2. npm install -D @pgtyped/cli typescript
  3. Install Runtime Dependency: Execute the command below to install the required runtime dependency.
  4. npm install @pgtyped/runtime
  5. Create Configuration File: You need to create a PgTyped configuration file named config.json.
  6. Run PgTyped in Watch Mode: Start PgTyped with the following command to track changes automatically.
  7. npx pgtyped -w -c config.json

For more details on getting started, check the Getting Started page.

Understanding the Code: An Analogy

To better understand how PgTyped works, let’s think of it as a smart librarian. Imagine a library full of books (your SQL database). Instead of manually cataloging every book by hand (mapping your DB schema to TypeScript), this librarian automatically sorts and categorizes every book as they come in (generating types from your Postgres database). This ensures that whenever a reader (your TypeScript code) wants a specific book (a query), they can simply ask, and the librarian will hand them the correct book with all its important details already known (guaranteed type safety).

Sample Code Implementation

Let’s take a look at a sample SQL query stored in books.sql:

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

This query will generate strict TypeScript types for parameters and results, ensuring you can catch errors during compilation rather than runtime.

To execute the generated query, the code would look something like this:

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

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();

Troubleshooting Common Issues

If you encounter any issues during setup or execution, consider the following troubleshooting steps:

  • Ensure that your Postgres database is running and accessible.
  • Double-check your config.json file for any misconfigurations.
  • Verify that all required dependencies are correctly installed.
  • Look out for TypeScript compile errors and match them with your query definitions.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Further Resources

To dig deeper into PgTyped, be sure to explore the following resources:

Conclusion

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox